【问题标题】:Why does using a reference inside of a match result in "cannot move out of dereference"?为什么在匹配中使用引用会导致“无法移出取消引用”?
【发布时间】:2014-06-23 11:34:57
【问题描述】:

编者注:此代码示例来自 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

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

【问题讨论】:

    标签: rust


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-06-04
      • 1970-01-01
      • 2022-11-25
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-11
      • 2020-04-11
      相关资源
      最近更新 更多