gpt4 book ai didi

rust - 为什么在匹配结果中使用引用会导致 "cannot move out of dereference"?

转载 作者:行者123 更新时间:2023-11-29 08:24:09 28 4
gpt4 key购买 nike

Editor's note: This code example is from a version of Rust prior to 1.0 and is not valid Rust 1.0 code. Updated versions of this code produce different errors, but the answers still contain valuable information.

我不明白为什么下面的代码不起作用。

use std::string::String;
use std::str;

fn append_byte_to_string(string: &String, bytes: &[u8]) {
let msg = str::from_utf8(bytes);
match msg {
Some(msg_str) => {
string.append("plop");//msg_str);
},
None => {}
}
}

fn main() {
append_byte_to_string(&String::new(), [64,65]);
}

我遇到了以下错误:

test.rs:8:4: 8:10 error: cannot move out of dereference of `&`-pointer
test.rs:8 string.append("plop");//msg_str);
^~~~~~
error: aborting due to previous error

我看过 explanations ,但我不明白它如何适用于我的代码。

最佳答案

您有一个&String:一个对String 对象的不可变 引用。您的方法需要采用 &mut String 才能改变字符串:

use std::str;

fn append_byte_to_string(string: &mut String, bytes: &[u8]) {
if let Ok(msg) = str::from_utf8(bytes) {
string.push_str(msg);
}
}

fn main() {
append_byte_to_string(&mut String::new(), &[64, 65]);
}

顺便说一句,你想要push_str而不是 append ,因为 append(或在 Rust 1.0 中,Add::add)使用它的参数并返回它,而 push_str 接受 &mut self

关于rust - 为什么在匹配结果中使用引用会导致 "cannot move out of dereference"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24364884/

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