这是来自铁 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()这样将互斥锁赋给_的时候,它会立即删除互斥锁吗?

推荐答案

_表示"不绑定此值".当您在现场创建新的价值时,这意味着价值会立即下降,就像您所说的那样,因为没有约束来拥有它.

当您将其与已绑定到某个变量的内容一起使用时,该值不会移动,这意味着该变量保留所有权.所以这个代码是有效的.

let guard = Guard;
let _ = guard;
let _a = guard; // `guard` still has ownership

这也很管用.

let two = (Guard, Guard);
print!("4");
let (_a, _) = two;
print!("3");
let (_, _b) = two;
print!("2");

当您希望在匹配后使用原始值时,这在Match语句中更有用,如果内部值被移动,这通常不起作用.

let res: Result<Guard, Guard> = Ok(Guard);
match res {
    Ok(ok) => drop(ok),
    Err(_) => drop(res), // do something with the whole `Result`
}

如果将第二个分支更改为Err(_e),则得到use of partially moved value: `res` .

Rust相关问答推荐

如何在不安全的代码中初始化枚举 struct

包含嵌套 struct 的CSV

使用Rust s serde_json对混合数据类型进行优化'

如何用Axum/Tower压缩Html内容?

有没有可能让泛型Rust T总是堆分配的?

为什么TcpListener的文件描述符和生成的TcpStream不同?

在铁 rust 中,如何一次只引用几件事中的一件?

Rust将String上的迭代器转换为&;[&;str]

为什么RefCell没有与常规引用相同的作用域?

Cargo.toml:如何有条件地启用依赖项功能?

Rust 中的复合 `HashSet` 操作或如何在 Rust 中获得 `HashSet` 的显式差异/并集

如何限制 GtkColumnView 行数

在 Rust 中忽略 None 值的正确样式

在线程中运行时,TCPListener(服务器)在 ip 列表中的服务器实例之前没有从客户端接受所有客户端的请求

类型判断模式匹配panic

如何展平以下嵌套的 if let 和 if 语句?

如何在 Rust 中返回通用 struct

TcpStream::connect - 匹配武器具有不兼容的类型

Rust 内联 asm 中的向量寄存器:不能将 `Simd` 类型的值用于内联汇编

加入动态数量的期货