Understanding the fundamental Rust - value doesn't live long enough

⚓ Rust    📅 2025-07-25    👤 surdeus    👁️ 2      

surdeus

I have the following fragment:

let line = match prev {
            None => {
                 let Ok(len) = stdin.read(&mut buffer) else {break};
                 String::from_utf8_lossy(&buffer[0..len])
            }
            Some(ref vec) => { 
              String::from_utf8_lossy(&vec)}
        };
        prev = None;
    // do something with line

It will complain that prev can't be reassigned because its content then used. It's fine and understandable. However, if I try to clone prev value like:

String::from_utf8_lossy(&vec.clone())

It complains that a temporary value doesn't live long enough. So generally I need to define the clone vector outside. So question is: why Rust can't make a life time of the inner value long enough to get it out the block and assigned?

2 posts - 2 participants

Read full topic

🏷️ Rust_feed