Lines<BufReader<File>>::count() takes ownership

Hi there!

I have following issue, where the count() method for some reasons takes ownership of the object, and returns nothing but size. According to this issue, I can't use this object in the iteration below:

let lines = BufReader::new(File::open(&argument.source)?).lines();

let mut index: HashMap<String, usize> = 
    HashMap::with_capacity(lines.count()); // `count` takes `lines` ownership

'l: for line in lines { // the `lines` moved (error)
  • I want to count the lines, to HashMap with optimal capacity, that based on this value.

It's impossible to count the elements in an arbitrary iterator without consuming the iterator in the process. To get the count and still be able to iterate over the elements, you need to either read the lines to memory or read through the file twice (and take into account that the file contents might have changed between the two reads). I wouldn't bother about the capacity given that the file I/O part is almost certainly going to be much slower than any amount of reallocations.

3 Likes

Thank you, I forgot that's unread buffer!

Yeah, BufReader doesn't buffer the whole file (well, except if the file is small).

1 Like