trpl-zh-cn/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs

15 lines
380 B
Rust
Raw Normal View History

2022-02-06 16:43:51 +08:00
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
}
// ANCHOR: here
fn calculate_length(s: &String) -> usize { // s is a reference to a String
s.len()
} // Here, s goes out of scope. But because it does not have ownership of what
// it refers to, nothing happens.
// ANCHOR_END: here