1
我的代碼:在「匹配」聲明「使用的部分移動值」錯誤
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
塊所有權。我只想在輸入enum的值之前輸入Vec
。我如何進行編譯?
工作,謝謝!我從來沒有見過「ref」之前。只能用於「匹配」塊嗎? 「ref」和「&」有什麼區別? – Michael
@Michael ['ref'用於模式](https://doc.rust-lang.org/book/patterns.html#ref-and-ref-mut)通過引用綁定到某個位置。 '&'模式位置用於*解構*引用,允許您訪問或綁定到位置*。 –
[本文](http://xion.io/post/code/rust-patterns-ref.html)可能有助於理解這種差異。 –