Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
fn take(s: String) {
println!("{s}");
}
fn main() {
let s = String::from("hi");
take(s);
println!("{s}");
}It does not compile
- Expecting
hi hi: a parameter of typeStringtakes ownership of the argument, so aftertake(s)the variablesis moved and cannot be used. - Expecting the string to come back when
takereturns: it is freed at the end oftake; to keep it, return it fromtakeor passs.clone().
- How would you change
takeso thatmaincan still printsafter the call? - What would change if
takereturned theStringit received?