使用dbg!()后出现‘borrow of moved value here’错误的原因?
Rust代码"borrow of moved value"错误原因及解决
问题代码
fn main() { // --snip-- let mut unit = String::new(); std::io::stdin() .read_line(&mut unit) .expect("couldn't read line!"); let unit = unit.trim().to_lowercase(); dbg!(unit); if unit == "f" { println!("temperature in Celsius is : {}°c", f_to_c(temp)); } else if unit == "c" { println!("temperature in Fahrenheit is : {}°f", c_to_f(temp)); } else { println!("'{unit}' unit not supported!"); } }
错误信息
error[E0382]: borrow of moved value: `unit` --> src/lib.rs:16:8 | 13 | let unit = unit.trim().to_lowercase(); | ---- move occurs because `unit` has type `String`, which does not implement the `Copy` trait 14 | dbg!(unit); | ---------- value moved here 15 | 16 | if unit == "f" { | ^^^^ value borrowed here after move
错误原因
这是Rust所有权规则导致的:
String未实现Copytrait,这类类型在传递给函数/宏时会触发所有权转移(move)。dbg!宏按值接收参数,调用dbg!(unit)时,unit的所有权被转移给宏,宏执行完后该String会被销毁。- 后续
if unit == "f"试图使用已经失去所有权的变量,因此触发错误。 - 错误和你显式声明
String类型无关,是所有权机制的必然结果。
修复方案
有两种常用修复方式:
方式1:传递引用给dbg!
将dbg!(unit)改为dbg!(&unit),仅传递不可变引用,不转移所有权,后续代码可正常使用unit:
let unit = unit.trim().to_lowercase(); dbg!(&unit); // 传递引用,保留原变量所有权 if unit == "f" { // 后续逻辑不变 }
方式2:克隆变量后传给dbg!
如果需要转移所有权给dbg!,可先克隆一份变量,原变量所有权保留:
let unit = unit.trim().to_lowercase(); dbg!(unit.clone()); // 克隆后传递,原变量可继续使用 if unit == "f" { // 后续逻辑不变 }
内容的提问来源于stack exchange,提问作者0ussamaBernou
相关产品推荐
相关产品推荐

