trpl-zh-cn/listings/ch04-understanding-ownership/listing-04-03/src/main.rs

24 lines
954 B
Rust
Raw Normal View History

2022-02-06 16:43:51 +08:00
fn main() {
2022-02-06 23:46:50 +08:00
let s = String::from("hello"); // s 进入作用域
2022-02-06 16:43:51 +08:00
2022-02-06 23:46:50 +08:00
takes_ownership(s); // s 的值移动到函数里 ...
// ... 所以到这里不再有效
2022-02-06 16:43:51 +08:00
2022-02-06 23:46:50 +08:00
let x = 5; // x 进入作用域
2022-02-06 16:43:51 +08:00
2022-02-06 23:46:50 +08:00
makes_copy(x); // x 应该移动函数里,
// 但 i32 是 Copy 的,
// 所以在后面可继续使用 x
2022-02-06 16:43:51 +08:00
2022-02-06 23:46:50 +08:00
} // 这里, x 先移出了作用域,然后是 s。但因为 s 的值已被移走,
// 没有特殊之处
2022-02-06 16:43:51 +08:00
2022-02-06 23:46:50 +08:00
fn takes_ownership(some_string: String) { // some_string 进入作用域
2022-02-06 16:43:51 +08:00
println!("{}", some_string);
2022-02-06 23:46:50 +08:00
} // 这里some_string 移出作用域并调用 `drop` 方法。
// 占用的内存被释放
2022-02-06 16:43:51 +08:00
2022-02-06 23:46:50 +08:00
fn makes_copy(some_integer: i32) { // some_integer 进入作用域
2022-02-06 16:43:51 +08:00
println!("{}", some_integer);
2022-02-06 23:46:50 +08:00
} // 这里some_integer 移出作用域。没有特殊之处