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
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.
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
}