gpt4 book ai didi

rust - 为什么一个整型变量在赋值给另一个变量后仍然可以使用?

转载 作者:行者123 更新时间:2023-12-02 01:26:31 24 4
gpt4 key购买 nike

我试图了解 Rust 中的所有权是如何运作的。考虑以下简单示例:

let u_own = 3432;
let d_own = u_own;
println!("{}", u_own);

尽管值 3432 的所有权已移至 d_own,但编译器不会提示。最后一条语句 println! 在控制台上打印数字 3432,没有任何问题。

我原以为编译器会提示,因为所有权已被转移。

最佳答案

所有权永远不会移动。对于任何标记为 std::marker::Copy 的类型(我们称该类型“是 Copy”),赋值运算符不会移动所有权。它创建该值的副本。

默认情况下,Rust 中的原始类型是“复制”的,您可以自由地在您自己的任何类型上派生该标记,但您应该为小型类型保留它。简单的枚举通常是 复制

如果您使用的类型不是Copy,那么将会出现您预期的行为。例如。一个字符串:

fn main() {
let u_own = String::new();
let d_own = u_own;
println!("{}", u_own);
}

playground

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`.

关于rust - 为什么一个整型变量在赋值给另一个变量后仍然可以使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74503570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com