Method chaining doesn't free owned strings when not bound?

Take this example:

let mut buf = String::new();
std::io::stdin().read_line(&mut buf).unwrap();
let input: Vec<&str> = buf.trim().to_lowercase().split_whitespace().collect();

trim returns a string slice then to_lowercase takes that and returns a new owned string, let's call it X, then split_whitespace takes that and returns and iterator then we collect it into a vector of slices.

This surprisingly works, what happened to X that was produced by to_lowercase? it wasn't bound to any variable, so basically the entries of Input are slices referencing a string that we can't access and don't even know where it is.

Why wasn't it dropped? and where can I read more about this behavior?

The string is a temporary inside the expression and is dropped at the end of the statement. Mara has a rather in-depth blog post about temporaries and their behaviour.

5 Likes

I just tried to print it afterwards, it invalidated the input as it should've, I forgot to print it afterwards to see if input is actually valid, so X had to be captured by some variable in order for the slices of it to be valid, Thanks.

EDIT: I just found out the only reason it compiled was because input wasn't being used afterwards.

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.