将boxed迭代器返回到结构中的值

时间:2017-07-27 19:45:05

标签: iterator rust

我想在一个struct上运行一个函数,它将一个迭代器返回给一个struct的成员。我试过类似下面的东西,但是没有用。

struct Foo {
    bar: Vec<String>,
}

impl Foo {
    fn baz(&self) -> Box<Iterator<Item = &String>> {
        Box::new(self.bar.iter())
    }
}

fn main() {
    let x = Foo { bar: vec!["quux".to_string()] };
    x.baz();
}

编译时,我收到以下错误:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
 --> src/main.rs:7:27
  |
7 |         Box::new(self.bar.iter())
  |                           ^^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 6:5...
 --> src/main.rs:6:5
  |
6 | /     fn baz(&self) -> Box<Iterator<Item = &String>> {
7 | |         Box::new(self.bar.iter())
8 | |     }
  | |_____^
note: ...so that reference does not outlive borrowed content
 --> src/main.rs:7:18
  |
7 |         Box::new(self.bar.iter())
  |                  ^^^^^^^^
  = note: but, the lifetime must be valid for the static lifetime...
note: ...so that expression is assignable (expected std::boxed::Box<std::iter::Iterator<Item=&std::string::String> + 'static>, found std::boxed::Box<std::iter::Iterator<Item=&std::string::String>>)
 --> src/main.rs:7:9
  |
7 |         Box::new(self.bar.iter())
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^

我还尝试按其他地方的建议添加生命周期信息

struct Foo {
    bar: Vec<String>,
}

impl Foo {
    fn baz<'a>(&self) -> Box<Iterator<Item = &String> + 'a> {
        Box::new(self.bar.iter())
    }
}

fn main() {
    let x = Foo { bar: vec!["quux".to_string()] };
    x.baz();
}

现在我的错误如下:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
 --> src/main.rs:7:27
  |
7 |         Box::new(self.bar.iter())
  |                           ^^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 6:5...
 --> src/main.rs:6:5
  |
6 | /     fn baz<'a>(&self) -> Box<Iterator<Item = &String> + 'a> {
7 | |         Box::new(self.bar.iter())
8 | |     }
  | |_____^
note: ...so that reference does not outlive borrowed content
 --> src/main.rs:7:18
  |
7 |         Box::new(self.bar.iter())
  |                  ^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the method body at 6:5...
 --> src/main.rs:6:5
  |
6 | /     fn baz<'a>(&self) -> Box<Iterator<Item = &String> + 'a> {
7 | |         Box::new(self.bar.iter())
8 | |     }
  | |_____^
note: ...so that expression is assignable (expected std::boxed::Box<std::iter::Iterator<Item=&std::string::String> + 'a>, found std::boxed::Box<std::iter::Iterator<Item=&std::string::String>>)
 --> src/main.rs:7:9
  |
7 |         Box::new(self.bar.iter())
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^

0 个答案:

没有答案