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

前端 未结 6 523
孤街浪徒
孤街浪徒 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:21

    Itertools has .format() for the purpose of lazy formatting, which skips allocating a string too.

    use std::io::BufRead;
    use itertools::Itertools;
    
    fn main() {
        let stdin = std::io::stdin();
        for line in stdin.lock().lines().map(|x| x.unwrap()) {
            println!("{}", line.split(' ').format(","));
        }
    }
    

    A digression, something like this is a “safe abstraction” in the littlest sense of the solution in another answer here:

    fn repurpose<'a, T: ?Sized>(mut v: Vec<&T>) -> Vec<&'a T> {
        v.clear();
        unsafe {
            transmute(v)
        }
    }
    

提交回复
热议问题