gpt4 book ai didi

rust - "use of partially moved value"语句中的 "match"错误

转载 作者:行者123 更新时间:2023-11-29 08:03:06 25 4
gpt4 key购买 nike

我的代码:

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 block 中发生了变化。我只想在将枚举添加到 Vec 之前输出枚举的值。我该如何编译?

最佳答案

按引用而不是按值绑定(bind)到 message 字段。

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

关于rust - "use of partially moved value"语句中的 "match"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38553513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com