[英]Rust compilation error: 'move occurs because `self.styles` has type `HashMap<&str, &str>`'
I have been trying to write simple logger "class" that can display test message in colors.我一直在尝试编写简单的记录器“类”,它可以在 colors 中显示测试消息。 I am running into the compilation error.我遇到了编译错误。 What am i doing wrong and how can i fix it?我做错了什么,我该如何解决? (please note i'd like to fix this particular issue not to replace what i am doing with some coloring crate, etc... it's a learning exercise for me). (请注意,我想解决这个特殊问题,而不是用一些着色箱等代替我正在做的事情......这对我来说是一个学习练习)。
error[E0507]: cannot move out of `self.styles` which is behind a shared reference
--> src/main.rs:21:30
|
21 | for (style, term) in self.styles {
| ^^^^^^^^^^^ move occurs because `self.styles` has type `HashMap<&str, &str>`, which does not implement the `Copy` trait
Code...代码...
use std::collections::HashMap;
struct Logger <'a> {
styles: HashMap<&'a str, &'a str>,
}
impl Logger <'_> {
fn new() -> Logger <'static> {
let mut logger = Logger{styles: HashMap::new()};
logger.styles.insert("</>", "\x1b[0m");
logger.styles.insert("<WARN>", "\x1b[1m\x1b[93m");
logger.styles.insert("<CRIT>", "\x1b[41m");
logger.styles.insert("<INFO>", "\x1b[1m");
logger
}
fn log(&self, message: &str) {
let mut output = String::new();
for (style, term) in self.styles {
output = message.replace(style, term);
}
println!("{}", output)
}
}
fn main() {
let logger = Logger::new();
logger.log("<INFO>Logger</> written in <CRIT>Rust</> language, <WARN>2021</>");
}
The for loop has an implicit call to .into_iter()
. for 循环隐式调用.into_iter()
。 From the docs (emphasis mine):从文档(强调我的):
Creates a consuming iterator, that is, one that moves each key-value pair out of the map in arbitrary order.创建一个消费迭代器,即以任意顺序将每个键值对移出 map 的迭代器。 The map cannot be used after calling this. map 调用后无法使用。
So the for loop is trying to move self.styles
since it doesn't implement the Copy
trait.所以 for 循环试图移动self.styles
因为它没有实现Copy
特征。 Try borrowing instead:尝试借用:
for (&style, &term) in &self.styles {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.