"使用部分移动的值"错误"匹配"声明

时间:2016-07-24 15:10:53

标签: rust

我的代码:

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

看起来message字段中match字段的所有权发生了变化。我只想在将其添加到Vec之前输出枚举值。我如何进行编译?

1 个答案:

答案 0 :(得分:6)

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

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