Rust:返回一个引用当前函数拥有的数据的值
我有一小段代码。为什么第二个无法编译Rust:返回一个引用当前函数拥有的数据的值,rust,compiler-errors,iterator,Rust,Compiler Errors,Iterator,我有一小段代码。为什么第二个无法编译 fn apply (&self, text: Text) -> Text { // works fine let mut data = String::new(); for c in text.data.chars() { let c = *self.mapping.get(&c).unwrap_or(&c); data.push(c); } return
fn apply (&self, text: Text) -> Text {
// works fine
let mut data = String::new();
for c in text.data.chars() {
let c = *self.mapping.get(&c).unwrap_or(&c);
data.push(c);
}
return Text {
data,
};
// not compile
return Text {
data: text.data.chars().map(|c| self.mapping.get(&c).unwrap_or(&c)).collect(),
};
}
编译器会详细地告诉您原因(这就是为什么读取和发布编译错误非常有用:
8 | data: text.data.chars().map(|c| self.mapping.get(&c).unwrap_or(&c)).collect()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--^
| | |
| | `c` is borrowed here
| returns a value referencing data owned by the current function
如果映射中不存在输入char
,它将返回一个对局部变量的引用,该引用是不允许的,因为该引用将被保留,这是rust不允许的
该解决方案与“works fine”版本中使用的解决方案完全相同:取消引用回调的结果,它将将&char
复制到char
,该char属于所有,因此可以返回,而不必考虑生存期问题:
文本{
数据:text.data.chars()
}
或者,您可以复制HashMap::get
的结果,生成一个选项
,然后将其展开或'd到字符
,修复问题的原因相同:
文本{
数据:text.data.chars()
}
您能否在问题中包含编译器错误,和/或提供一个我们可以尝试的独立示例?