不明白这段代码上的移动/复制特征错误:Rust



以下代码来自 Packt 中的练习,掌握 Rust 2nd Edition,但没有给出解决方案。这本书有点旧,也许编译器发生了变化。 问题是"word_counter.increment(word(;"行,编译器抱怨复制特征未实现。但我看不出哪里有举动。

// 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

increment的签名是

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

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

相关内容

最新更新