Temporary value dropped while borrowed. Weird!

error[E0425]: cannot find value buffer_iter in this scope
--> src\myfs.rs:42:26
|
42 | println!("{:?}", buffer_iter);
| ^^^^^^^^^^^ not found in this scope

For more information about this error, try rustc --explain E0425.
error: could not compile my_project (bin "my_project") due to 1 previous error

pub fn test_read_file(){
    let file_path = "./data/file01.txt";
    let read_file_result = fs::read(file_path);

    if read_file_result.is_ok(){

        let buffer = read_file_result.unwrap().iter();
        println!("{:?}", buffer_iter);


    }
    else{
        println!("Some problem occured reading files: {:?}", read_file_result.err());
        
    }

    
}

This version compiler didn't complain.

pub fn test_read_file(){
    let file_path = "./data/file01.txt";
    let read_file_result = fs::read(file_path);

    if read_file_result.is_ok(){
        let buffer = read_file_result.unwrap();
        let buffer_iter = buffer.iter();
        println!("{:?}", buffer_iter);


    }
    else{
        println!("Some problem occured reading files: {:?}", read_file_result.err());
        
    }

    
}

Why????

1 Like

Vec::iter takes the vector by reference. This does not work when the vector is a temporary value, because temporaries are dropped at the end of the statement. I.e. in your case the vector you try to borrow from is dropped

let buffer = read_file_result.unwrap().iter();
                                             ^ right here,

which'd make the iterator dangle. This is like trying to return a reference from a local value from a function. The local value is dropped when the function returns, so no sound way to return a reference to it. In your second example you bind the vector to a variable which cause the vector to be dropped when the variable goes out of scope, so its fine for you to borrow from it.

A great read on temporaries is Mara Bos' introductory blog post for super let:

Try using Vec::into_iter which takes ownership of the data from the vector, instead of borrowing.

3 Likes