If program leave loop, does program loses ownership of the variable?


I wrote the code as shown in the picture above. If I take the code "let mut s = String::new();" out of the loop, the compilation will be fine, and the program will stop working while running through the second loop. Why does this happen? Is it because every time program turns a new loop, program loses ownership of the variable s?

The read_line method will append to the string, so you probably need to clear it at the start of each iteration when it is moved outside the loop.

Additionally, pushing it to a vector gives away ownership of the string.

This seems to be irrelevant here, since the vector holds not strings, but u32s, parsed from that strings.

I typed the program in:

use std::io;

fn main(){
    let mut v = Vec::new();
    v.push(1);
    loop {
         let mut s = String::new();
         println!( "isloop!????" );
         io::stdin().read_line(&mut s)
             .expect("Failed to read line");
         let s: u32 = s.trim().parse()
             .expect("Please type number");
         if s==0 { break; }
         v.push( s );
          println!("{:?}",v)
    }
}

and it worked ok.

What do you mean by "the program will stop working while running through the second loop" ?

Please do not post code as images. Code in images cannot be copied and is hard to read.

4 Likes

Every set of curly braces introduces a new scope and when you exit a scope (i.e. at the }) all variables will be dropped. That means each s string is a new String object and you won't be able to use the string from the last loop.

I'm sorry, I won't ask the community this way from now on.

Check out this thread, it provides some examples of how to write code in comments.

You can also use the "Share" button on the playground to link to a runnable copy of your code.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.