Borrow checker doesn't realize that `clear` drops reference to local variable

前端 未结 6 519
孤街浪徒
孤街浪徒 2020-12-06 16:22

The following code reads space-delimited records from stdin, and writes comma-delimited records to stdout. Even with optimized builds it\'s rather slow (about twice as slow

6条回答
  •  無奈伤痛
    2020-12-06 17:00

    Another approach is to refrain from storing references altogether, and to store indices instead. This trick can also be useful in other data structure contexts, so this might be a nice opportunity to try it out.

    use std::io::BufRead;
    
    fn main() {
        let stdin = std::io::stdin();
        let mut cache = Vec::new();
        for line in stdin.lock().lines().map(|x| x.unwrap()) {
            cache.push(0);
            cache.extend(line.match_indices(' ').map(|x| x.0 + 1));
            // cache now contains the indices where new words start
    
            // do something with this information
            for i in 0..(cache.len() - 1) {
                print!("{},", &line[cache[i]..(cache[i + 1] - 1)]);
            }
            println!("{}", &line[*cache.last().unwrap()..]);
            cache.clear();
        }
    }
    

    Though you made the remark yourself in the question, I feel the need to point out that there are more elegant methods to do this using iterators, that might avoid the allocation of a vector altogether.

    The approach above was inspired by a similar question here, and becomes more useful if you need to do something more complicated than printing.

提交回复
热议问题