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

前端 未结 6 520
孤街浪徒
孤街浪徒 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 16:58

    The safe solution is to use .drain(..) instead of .clear() where .. is a "full range". It returns an iterator, so drained elements can be processed in a loop. It is also available for other collections (String, HashMap, etc.)

    fn main() {
        let mut cache = Vec::<&str>::new();
        for line in ["first line allocates for", "second"].iter() {
            println!("Size and capacity: {}/{}", cache.len(), cache.capacity());
            cache.extend(line.split(' '));
            println!("    {}", cache.join(","));
            cache.drain(..);
        }
    }
    

提交回复
热议问题