首页 > 解决方案 > 通过特征获取结构的引用

问题描述

我有以下代码(指向 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),但我不知道该怎么做。

提前致谢

标签: rust

解决方案


难道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 )


推荐阅读