rust - 通过特征获取结构的引用
问题描述
我有以下代码(指向 Rust 游乐场的链接):
struct News {
size: u32,
date: &'static str,
}
struct Journal {
lst_news: Vec<News>,
}
trait GetNews {
fn get_news(&self) -> Vec<&News>;
}
impl GetNews for Journal {
fn get_news(&self) -> Vec<&News> {
let mut news_list: Vec<&News> = Vec::new();
for ii in &self.lst_news {
news_list.push(ii)
}
news_list
}
}
fn news_filter<T: GetNews>(media: T) -> Vec<&News> {
let mut news_list: Vec<&News> = Vec::new();
for ii in media.get_news() {
news_list.push(ii)
}
news_list
}
当我编译代码时,出现以下错误:
Compiling playground v0.0.1 (/playground)
error[E0106]: missing lifetime specifier
--> src/lib.rs:38:45
|
38 | fn news_filter<T: GetNews>(media: T) -> Vec<&News> {
| ^ help: consider giving it an explicit bounded or 'static lifetime: `&'static`
|
= help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments
我试图根据借用检查器修复它,如下所示:
fn news_filter<T: 'static + GetNews>(media: T) -> Vec<&'static News> {
let mut news_list: Vec<&News> = Vec::new();
for ii in media.get_news() {
news_list.push(ii)
}
news_list
}
我得到了这个:
Compiling playground v0.0.1 (/playground)
error[E0515]: cannot return value referencing function parameter `media`
--> src/lib.rs:43:5
|
40 | for ii in media.get_news() {
| ----- `media` is borrowed here
...
43 | news_list
| ^^^^^^^^^ returns a value referencing data owned by the current function
我不知道如何解决这个问题。我认为好的方法是引用向量(news_list),但我不知道该怎么做。
提前致谢
解决方案
难道news_filter
真的要按值取值吗?这样,里面的东西在T
被函数消费后就不能被引用了。
我想你其实想要fn news_filter<T: GetNews>(media: &T) -> Vec<&News>
。(游乐场链接:https ://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b0e387ab264d98979ab3e68057401349 )
推荐阅读
- git - “git clone git://”和“git clone https://”有什么区别?
- mainframe - ISPF 重新连接成功但不显示 ISPF 主选项菜单
- javascript - 试图获取 guildMember.presence.status 的 discord.js 导致“无法读取未定义的属性(读取 'status')”
- r - 如何使用 dplyr 对这些变量进行分组以进行分组汇总?
- python - 计算数据帧(熊猫)中每一列/行的平均值的 lambda 函数是什么?
- c++ - 编译错误:未定义的引用,主要是与库的依赖引起的?
- rust-cargo - 货物说“测试失败,重新运行通过'--lib” - 这是什么意思?
- compiler-construction - 构建 AST 时处理错误和释放内存的策略
- java - LibGDX 将 2D 精灵绘制到 3D 环境中
- reactjs - 无法在反应js axios中获取响应代码