我的代码:
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
之前输出枚举值。我如何进行编译?
答案 0 :(得分:6)
通过引用绑定到message
字段而不是按值。
match msg {
Message::Write{ref message} => println!("{}", message),
};