我试图了解 Rust 中的所有权是如何运作的。考虑以下简单示例:
let u_own = 3432;
let d_own = u_own;
println!("{}", u_own);
Run Code Online (Sandbox Code Playgroud)
编译器不会抱怨,尽管该值的所有权3432已转移到d_own. 最后一条语句在控制台上println!打印数字没有任何问题。3432
我原以为编译器会抱怨,因为所有权已被转移。
所有权永远不会移动。对于任何标记为的类型std::marker::Copy(我们称该类型“是复制”),赋值运算符不会移动所有权。它创建该值的副本。
Rust 中的原始类型是Copy默认的,您可以自由地在您自己的任何类型上派生该标记,但您应该为小型类型保留它。通常会进行简单的枚举Copy。
如果您使用的类型不是Copy,那么将会出现您预期的行为。例如String:
fn main() {
let u_own = String::new();
let d_own = u_own;
println!("{}", u_own);
}
Run Code Online (Sandbox Code Playgroud)
error[E0382]: borrow of moved value: `u_own`
--> src/main.rs:4:20
|
2 | let u_own = String::new();
| ----- move occurs because `u_own` has type `String`, which does not implement the `Copy` trait
3 | let d_own = u_own;
| ----- value moved here
4 | println!("{}", u_own);
| ^^^^^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0382`.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |