非匹配机构是否以“匹配"方式获取变量的所有者?Rust中的声明? [英] Does non-matching arm take the owner of a variable in a "match" statement in Rust?

查看:61
本文介绍了非匹配机构是否以“匹配"方式获取变量的所有者?Rust中的声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Rust的新手.以下是我的测试.

I'm new to Rust. Below is my testing.

#[derive(Debug)]
enum Food {
    Cake,
    Pizza,
    Salad,
}

#[derive(Debug)]
struct Bag {
    food: Food
}

fn main() {
    let bag = Bag { food: Food::Cake };
    match bag.food {
        Food::Cake => println!("I got cake"),
        x => println!("I got {:?}", x)
    }

    println!("{:?}", bag);
}

运行时出现错误.

error[E0382]: borrow of moved value: `bag`
  --> src\main.rs:20:22
   |
17 |         x => println!("I got {:?}", x)
   |         - value moved here
...
20 |     println!("{:?}", bag);
   |                      ^^^ value borrowed here after partial move
   |
   = note: move occurs because `bag.food` has type `Food`, which does not implement the `Copy` trait

很明显, bag.food 与代码中的 x 臂不匹配.为什么在这里发生移动?

It's clear that bag.food will not match x arm in the code. Why a move happens there?

推荐答案

在运行时不采用 x 分支无关紧要,因为是否使用 match 其参数的所有权不取决于实际将采用 match 的哪个分支.类似于此代码(另请参见

It doesn't matter that the x branch is not taken at runtime because whether a match takes ownership of its argument does not depend on which branch of the match will actually be taken. Much like in this code (also see this followup question):

let foo = "blargh".to_owned();
if false {
    let _bar = foo;
}
println!("{}", foo); // error[E0382]: borrow of moved value: `foo`

foo 从未真正移动过,但这与 if 之后(是否无效)之后是否有效没有任何区别.

foo is never actually moved, but that doesn't make any difference to whether it is valid after the if (it isn't).

问题中的 match 拥有 bag.food 的所有权(使 bag 无效),因为它有一个拥有所有权的分支.如果您不希望该特定分支拥有所有权,则可以使用 ref 模式来借用:

The match in the question takes ownership of bag.food (invalidating bag) because it has a branch that takes ownership. If you want that particular branch to not take ownership, you can use a ref pattern to borrow instead:

match bag.food {
    Food::Cake => println!("I got cake"),
    ref x => println!("I got {:?}", x)
}

或者,从Rust 1.26开始,编译器知道如何将值模式(例如 Food :: Cake )绑定到引用(例如& bag.food ),所以你可以这样写:

Alternatively, since Rust 1.26 the compiler knows how to bind value patterns (such as Food::Cake) to references (such as &bag.food), so you can write:

match &bag.food {
    Food::Cake => println!("I got cake"),
    x => println!("I got {:?}", x)
}

在这种情况下, Food :: Cake 匹配值,但是 x 匹配并绑定到引用,因此它与带有 ref .(您可能会将此称为默认绑定模式"或匹配人体工程学".)

In this case Food::Cake matches the value, but x matches and is bound to the reference, so it does the same thing as the previous snippet with ref. (You may see this referred to as "default binding modes" or "match ergonomics".)

这篇关于非匹配机构是否以“匹配"方式获取变量的所有者?Rust中的声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆