Confused by compilation error between rustc versions

#1

Hi guys, I wrote a program which compiles and runs fine under rust 1.32. However this program solves a problem on the Timus online judge which only uses rust version 1.25, so when I submit the program to Timus I get a compiling error.

The significant part of the program is

fn main() {
    let mut index = BTreeSet::<Path>::new();
    let in_stream = stdin();    
    let mut paths_count_line = String::new();
    in_stream.read_line(&mut paths_count_line).unwrap();
    let stdin = stdin();
    let lines: Vec<String> = stdin.lock().lines().filter_map(|line| line.ok()).collect();        
    let splits: Vec<Vec<&str>> = lines.iter().map(|line| line.split("\\").collect()).collect();        
    for split in &splits{
        for path in Path::new(split) {
            index.insert(path);
        }        
    }
    for p in index.iter() {
        println!("{}", p);
    }
}

where the Path struct is something like (I could post the entire code if needed)

#[derive(Debug, PartialEq, Eq)]
struct Path<'a> {
    components: &'a [&'a str],
}

impl<'a> Path<'a> {
    fn new(path:&'a Vec<&str> ) -> Vec<Self> {        
        let mut result = Vec::<Path>::with_capacity(path.len());
        for i in 0..path.len() {
            let slice = &path[0..(i + 1)];
            result.push(Path { components: slice });
        }
        result
    }
}

The errors I got when timus compiles with 1.25 are:

error[E0597]: `lines` does not live long enough
   --> rknu43-wrtu6q:101:38
    |
101 |         let splits: Vec<Vec<&str>> = lines
    |                                      ^^^^^ borrowed value does not live long enough
...
116 | }
    | - `lines` dropped here while still borrowed
    |
    = note: values in a scope are dropped in the opposite order they are created

error[E0597]: `splits` does not live long enough
   --> rknu43-wrtu6q:106:27
    |
106 |             for split in &splits {
    |                           ^^^^^^ borrowed value does not live long enough
...
115 |     }
    |     - `splits` dropped here while still borrowed
116 | }
    | - borrowed value needs to live until here

error: aborting due to 2 previous errors

Can somebody explain to me, how should I change the code in order to compile on rust 1.25?
Thank you!

0 Likes

#2

In v1.31 Rust’s borrow checker became smarter (added support for so-called non-lexical lifetimes), so it’s able to understand that this program is OK. Older Rust versions are much more pedantic need workarounds.

Try creating index after creating splits.

0 Likes

#3

That was the issue.
Thank you very much!

0 Likes