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

  • 本文关键字:cannot move out dereference of 引用 rust
  • 更新时间 :
  • 英文 :


编者按:此代码示例来自Rust 1.0之前的版本,不是有效的Rust 1.0代码。此代码的更新版本会产生不同的错误,但答案仍然包含有价值的信息。

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

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

我看到了一些解释,但我不明白它如何适用于我的代码。

您有一个&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

相关内容

最新更新