Extending borrowed lifetime for String slice

前端 未结 2 413
后悔当初
后悔当初 2020-12-12 00:39

I have a function that reads in a file, and for each line adds it to a HashSet of type &str, but I can\'t work out how to tell the borrow check

2条回答
  •  失恋的感觉
    2020-12-12 01:01

    reader.lines() returns an iterator over owned Strings. But then in your for loop you cast these to borrowed references to &str. So when the iterator goes out of scope all your borrowed references become invalid. Consider using a HashSet instead, which also is zero cost, because the Strings get moved into the HashSet and therefore aren't copied.

    Working example

    fn build_collection_set(reader: &mut BufReader) -> HashSet {
        let mut collection_set: HashSet = HashSet::new();
    
        for line in reader.lines() {
            let line = line.unwrap();
            if line.len() > 0 {
                collection_set.insert(line);
            }
        }
        collection_set
    }
    

提交回复
热议问题