Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
fn make() -> &String {
let s = String::from("hi");
&s
}
fn main() {
let r = make();
println!("{}", r.len());
}It does not compile
- Expecting
2: a reference does not keep its value alive, andsis dropped whenmakereturns, so the compiler refuses-> &Stringwith E0106. - Expecting garbage or an empty string at run time: safe Rust never reads freed memory, because a dangling reference does not get past the compiler.
- How would you change
makeso that the program compiles and prints2? - Which error appears if the signature is changed to
-> &'static String?