I have a function that takes one parameter, a string and returns a string reference of the clone of that string parameter. The binary however doesn't compile. The debugger requests that I change the string reference. What Im I fundamentally missing in this setup. Here is the code
fn taker (S:String) -> &String {
let c = S.clone();
&c
}
fn main () {
let V = taker("Value".to_string());
println!(".. {:?}",V);
}
You're missing the fact that c is a variable local to the function taker, and will get dropped when the function returns. &c would be a dangling reference then, so that would certainly be an error if the compiler didn't keep you from making it.
You can never return references to function-local variables. c is dropped at the end of taker, making the reference you try to return from taker immediately dangling.
In Rust, & has a more specific role than just returning by reference (Box is also a pointer type and can be used to store or return by reference).
& creates a temporary permission to view data that has already been stored somewhere. It doesn't move the data anywhere.
& can never ever make anything live longer. It has no power to do anything. It's always limited by what the code is doing anyway.
In your case you end up trying to give a temporary permission to view the c variable. The String is not being returned. And the code doesn't compile, because the variable c will be destroyed before the function returns, and references have no power to change that.
The correct way is to return String itself, rather than a temporary permission to view the String sitting inside the function body.
Rust doesn't need & to avoid copying. Most types are non-Copy, and get moved instead of copied.
If the aim is to .clone() you could pass a reference, just as the compiler suggests, and then return the clone, and not a reference.
If the aim is to practice with a fn that takes ownership of the String, then yes, pass a String. Then you can just return the same string (owner is moved anyways), or clone and return.