代码之家  ›  专栏  ›  技术社区  ›  dpr

分配给下划线模式时会发生什么?

  •  5
  • dpr  · 技术社区  · 3 年前

    这是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 ,在主的第三行中,分配给 _ 意味着立即下降。但是,当将所有权转让给 _ 使用以下代码

    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 没有立即下降,而且 _ 拥有 警卫 ?

    所以我不确定何时将互斥对象分配给 _ 像这样 let _ = Mutex::lock().unwrap() ,它会立即放弃互斥吗?

    1 回复  |  直到 3 年前
        1
  •  38
  •   drewtato    3 年前

    _ 表示“不绑定此值”。当您当场创建一个新值时,这意味着该值会立即被丢弃,就像您所说的那样,因为没有绑定来拥有它。

    当您将它与已经绑定到变量的东西一起使用时,值不会移动,这意味着变量保留所有权。所以这个代码是有效的。

    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");
    

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

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

    推荐文章