trpl-zh-cn/listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs
2024-10-20 23:44:05 +08:00

15 lines
374 B
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{s1}' is {len}.");
}
// ANCHOR: here
fn calculate_length(s: &String) -> usize { // s 是 String 的引用
s.len()
} // 这里s 离开了作用域。但因为它并不拥有引用值的所有权,
// 所以什么也不会发生
// ANCHOR_END: here