我有一个生命周期问题,我正在尝试实现一个通过引用返回其项的迭代器,以下是代码:
struct Foo {
d: [u8; 42],
pos: usize
}
impl<'a> Iterator<&'a u8> for Foo {
fn next<'a>(&'a mut self) -> Option<&'a u8> {
let r = self.d.get(self.pos);
if r.is_some() {
self.pos += 1;
}
r
}
}
fn main() {
let mut x = Foo {
d: [1; 42],
pos: 0
};
for i in x {
println!("{}", i);
}
}
然而,这段代码无法正确编译,出现了与参数生命周期相关的问题,以下是相应的错误:
$ rustc test.rs
test.rs:8:5: 14:6 error: method `next` has an incompatible type for trait: expected concrete lifetime, but found bound lifetime parameter
test.rs:8 fn next<'a>(&'a mut self) -> Option<&'a u8> {
test.rs:9 let r = self.d.get(self.pos);
test.rs:10 if r.is_some() {
test.rs:11 self.pos += 1;
test.rs:12 }
test.rs:13 r
...
test.rs:8:49: 14:6 note: expected concrete lifetime is the lifetime 'a as defined on the block at 8:48
test.rs:8 fn next<'a>(&'a mut self) -> Option<&'a u8> {
test.rs:9 let r = self.d.get(self.pos);
test.rs:10 if r.is_some() {
test.rs:11 self.pos += 1;
test.rs:12 }
test.rs:13 r
...
error: aborting due to previous error
有没有人有解决这个问题并仍然返回项的引用的想法?
至少这条消息是什么意思:期望具体的生命周期,但发现绑定的生命周期参数?
Items
实际上是使用宏生成的,因此在你能够理解它之前,你需要了解Rust宏的基础知识!随时准备好访问irc://irc.mozilla.org/#rust,那里总有人可以提供帮助。 - Chris Morganimpl<'a> Iterator for Foo { // unconstrained lifetime parameter
。 - Jonas Berlin