我试图了解 Rust 中的所有权是如何运作的。考虑以下简单示例:
let u_own = 3432;
let d_own = u_own;
println!("{}", u_own);
编译器不会抱怨,尽管所有权来自值3432
已移至d_own
。最后一条语句是println!
打印号码3432
控制台上没有任何问题。
我原以为编译器会抱怨,因为所有权已被转移。
所有权永远不会移动。对于任何标记为的类型std::marker::Copy
(我们说类型“is Copy”),赋值运算符不会移动所有权。它创建该值的副本。
Rust 中的原始类型是Copy
默认情况下,您可以自由地在您自己的任何类型上派生该标记,但您应该为小型类型保留它。通常使用简单的枚举Copy
.
如果您使用的类型不是Copy
,那么你的预期行为就会出现。例如。 AString
:
fn main() {
let u_own = String::new();
let d_own = u_own;
println!("{}", u_own);
}
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`.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)