这是 Rust 测验 28 的一个问题:
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
print!("1");
}
}
fn main() {
let _guard = Guard;
print!("3");
let _ = Guard;
print!("2");
}
这段代码会打印出3121
,在main函数的第三行,将值赋给_
表示立即丢弃。然而,当使用以下代码将所有权转移给_
时:
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
print!("1");
}
}
fn main() {
let _guard = Guard;
print!("3");
let _ = _guard;
print!("2");
}
它打印出321
,这意味着Guard
没有立即释放,而_
拥有Guard
?
所以我不确定像这样将互斥锁分配给_
let _ = Mutex::lock().unwrap()
时,它是否会立即释放互斥锁?
guard;
会移动(并因此丢弃)guard
,而let _ = guard;
则不会导致移动。函数std::mem::drop()
实际上是多余的——drop(x);
和x;
是完全等价的。 - Sven Marnach