【问题标题】:Don't understand the Move/Copy trait error on this code : Rust不理解此代码上的移动/复制特征错误:Rust
【发布时间】:2020-09-08 17:59:48
【问题描述】:

以下代码来自 Packt,Mastering Rust 2nd Edition 中的一个练习,但没有给出解决方案。这本书有点旧,编译器可能已经发生了变化。 问题是“word_counter.increment(word);”编译器抱怨 Copy trait 未实现的行。但我看不出哪里有动作。

// word_counter.rs
use std::env;
use std::fs::File;
use std::io::prelude::BufRead;
use std::io::BufReader;
use std::collections::HashMap; 
#[derive(Debug)]
struct WordCounter(HashMap<String, u64>); //A New Type Idiom of Tuple Struct
impl WordCounter {
    pub fn new() -> WordCounter {
        let mut _cmd = WordCounter(HashMap::new());
        _cmd
    }
    pub fn increment(mut self, word: &str) {
        let key = word.to_string();
        let count = self.0.entry(key).or_insert(0);
        *count += 1;
    }
    pub fn display(self) {
        for (key, value) in self.0.iter() {
            println!("{}: {}", key, value);
        }
    }
}
fn main() {
    let arguments: Vec<String> = env::args().collect();
    let filename = &arguments[1];
    println!("Processing file: {}", filename);
    let file = File::open(filename).expect("Could not open file");
    let reader = BufReader::new(file);
    let word_counter = WordCounter::new();
    for line in reader.lines() {
        let line = line.expect("Could not read line");
        let words = line.split(" ");
        for word in words {
            if word == "" {
                continue
            } else {
                word_counter.increment(word);
            }
        }
    }
    word_counter.display();
}

游乐场错误:

   |
31 |     let word_counter = WordCounter::new();
   |         ------------ move occurs because `word_counter` has type `WordCounter`, which does not implement the `Copy` trait
...
40 |                 word_counter.increment(www);
   |                 ^^^^^^^^^^^^ value moved here, in previous iteration of loop

【问题讨论】:

    标签: rust


    【解决方案1】:

    increment的签名是

    pub fn increment(mut self, word: &str)
    

    它是mut self 而不是&amp;mut self 的事实意味着函数将消耗自己(它将self 移动到函数中)。因此,第一次调用移动值,第二次调用是非法的。

    【讨论】:

      猜你喜欢
      • 2022-12-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 2021-06-01
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多