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

15 lines
375 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
2022-10-13 13:31:29 +08:00
fn calculate_length(s: &String) -> usize { // s是String的引用
2022-02-06 16:43:51 +08:00
s.len()
2022-02-06 23:46:50 +08:00
} // 这里s 离开了作用域。但因为它并不拥有引用值的所有权,
// 所以什么也不会发生
2022-02-06 16:43:51 +08:00
// ANCHOR_END: here