Here, why cant we store returned value in longest so that even if str2 goes out scope we can still use longest and what is the way around these situations.
Because there can be many cases where I may need the returned value after it goes out of scope
In general: either make sure the pointed-to value lives long enough
fn main() {
let (longest, str2);
let str1 = String::from("Aysuhmaan");
{
str2 = String::from("Aysuhmaan Singh");
longest = longer(&str1, &str2);
}
println!("{longest}");
}
(playground)
or create a new copy of the data
fn main() {
let longest;
let str1 = String::from("Aysuhmaan");
{
let str2 = String::from("Aysuhmaan Singh");
longest = longer(&str1, &str2).to_owned();
}
println!("{longest}");
}
(playground)
Please post code as text:
```
Paste code here
```
Variables like str2 have drop scopes. If a variable isn't moved when control flow hits the end of the drop scope, it gets dropped (destructed) at that point. It's a borrow conflict for a variable to be borrowed when it gets dropped.
Borrow checking doesn't change the semantics of your code -- it's a pass or fail test -- so it can't change the drop scope of variables.
Depends on the situation. Maybe declare the value somewhere else, maybe use Rc<_> instead of references, maybe move the value instead of borrowing it, maybe clone it... there are many possibilities.
You can do this; it’s just not what the program is doing. Here is a program that does — it is transferring ownership of the original string:
fn main() {
let longest;
let str1 = String::from("Aysuhmaan");
{
let str2 = String::from("Aysuhmaan Singh");
longest = longer(str1, str2);
}
println!("{longest}");
}
fn longer(x: String, y: String) -> String {
if x.len() > y.len() { x } else { y }
}