Back to questions
JuniorTheoryCommon
What does the program print?
fn len(s: &String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = len(&s);
println!("{s} {n}");
}hello 5
- Expecting a compile error:
len(&s)passes a reference, not theString, so ownership stays withsandprintln!may still use it. - Expecting the string to be freed when
lenreturns: only the reference goes away, because the ownersis the one that frees the string.
- How would the program change if
lentooks: Stringinstead of&String? - Why is
&stra better parameter type than&Stringforlen?