解决 Rust 报错 error[E0382] use of moved value 指南
分析 Rust 编译器报错 error[E0382] use of moved value 的所有权机制与借用检查,提供引用借用与 clone 处理方案。
问题现象
编写 Rust 代码编译时被 rustc 拦截报错:
error[E0382]: use of moved value: `user_name`
--> src/main.rs:12:20
|
5 | let user_name = String::from("Alice");
| --------- move occurs because `user_name` has type `String`, which does not implement the `Copy` trait
6 | send_message(user_name);
| --------- value moved here
...
12 | println!("{}", user_name);
| ^^^^^^^^^ value used here after move
触发根因
- Rust 的所有权(Ownership)机制规定:未实现
Copytrait 的类型(如String、Vec)在传值给函数或赋值给其他变量时,所有权会发生转移(Move)。 - 在所有权已被转移之后,原变量名失效,再次访问该变量会触发编译错误
E0382。
解决步骤与操作命令
步骤一:改用不可变引用借用(Borrowing)
如果函数只需要读取数据,修改函数签名接收引用 &str 或 &T:
// 修改函数签名
fn send_message(msg: &str) {
println!("Sending: {}", msg);
}
fn main() {
let user_name = String::from("Alice");
send_message(&user_name); // 借用,不转移所有权
println!("Still valid: {}", user_name); // 正常编译
}
步骤二:显式深拷贝(.clone())
如果函数确实需要持有独立所有权,且性能非极端敏感,显式克隆副本:
send_message(user_name.clone());
println!("{}", user_name);
步骤三:针对自定义结构体实现 Copy / Clone
对于只包含基本标量类型的结构体,派生宏:
#[derive(Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
验证确认
再次运行代码检查:
cargo check
cargo build
编译器通过检查,成功生成二进制文件。


