rust - Rust:返回一个引用当前函数拥有的数据的值
问题描述
我有一小段代码。为什么第二个编译失败?
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 不允许的。
该解决方案与“正常工作”版本中使用的解决方案完全相同:取消引用回调的结果,该结果将Copy
指向&char
a char
,它是拥有的,因此可以在没有生命周期的情况下返回:
Text {
data: text.data.chars().map(|c| *self.mapping.get(&c).unwrap_or(&c)).collect()
}
或者,您可以产生一个'd to 'copied
的结果,出于相同的原因解决问题:HashMap::get
Option<char>
unwrap_or
char
Text {
data: text.data.chars().map(|c| self.mapping.get(&c).copied().unwrap_or(c)).collect()
}
推荐阅读
- matplotlib - 直方图的最后一个 bin 缺失
- css - 响应式 H1 大文本 - 不适用于 #index H1
- php - Sendgrid 动态模板 PHP
- swift - 更新到 Catalina 后的 Simd 错误 - Swift
- python - 清理 excel 文档 - 根据其内容格式化单元格
- javascript - 改变日历设计的内容方向
- unity3d - Unity Player 移动失败并且玩家旋转面对鼠标
- python - 如何在不同线程中将 matplotlib 图形绘制到 tkinter 画布上
- javascript - 关闭模态前的保存/取消提示(当模态已被 ESC/单击背景关闭时)
- python-3.x - 在python中对没有返回值的函数进行单元测试