【问题标题】:"use of partially moved value" error in "match" statement“匹配”语句中的“使用部分移动的值”错误
【发布时间】:2016-07-24 15:10:52
【问题描述】:

我的代码:

fn main() {
    let mut messages = vec![];

    let msg = Message::Write{message: "msg".to_string()};
    match msg {
        Message::Write{message} => println!("{}", message),
    };

    messages.push(msg);
}

enum Message {
    Write{message: String},
}

错误:

error: use of partially moved value: `msg` [--explain E0382]
   --> <anon>:9:19
6   |>         Message::Write{message} => println!("{}", message),
    |>                        ------- value moved here
...
9   |>     messages.push(msg);
    |>                   ^^^ value used here after move
note: move occurs because `msg.message` has type `std::string::String`, which does not implement the `Copy` trait

error: aborting due to previous error

看起来match 块中message 字段的所有权发生了变化。我只是希望能够在将枚举添加到Vec 之前输出它的值。如何编译?

【问题讨论】:

    标签: rust


    【解决方案1】:

    通过引用而不是按值绑定到message 字段。

        match msg {
            Message::Write{ref message} => println!("{}", message),
        };
    

    【讨论】:

    • 成功了,谢谢!我以前从未见过“参考”。只能在“匹配”块中使用吗? “ref”和“&”有什么区别?
    • @Michael ref is used in patterns 通过引用绑定到位置。模式位置中的&amp; 用于解构一个引用,允许您访问或绑定到它后面的位置。
    • This article 可能有助于理解差异。
    猜你喜欢
    • 1970-01-01
    • 2017-07-04
    • 2018-05-01
    • 1970-01-01
    • 2023-04-05
    • 2020-04-19
    • 2018-09-27
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多