我有一个结构A
,其中有一个字符串字段string
:
struct A<'a> {
string: String,
//some other field which needs the lifetime specifier
}
我想实现Iterator
以返回string
的一部分。
impl<'a> Iterator for A<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
//do something to get the index `x` and `y`
return Some(&self.string[x .. y]);
}
}
编译器说:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/main.rs:11:22
|
11 | return Some(&self.string[x .. y]);
| ^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 8:5...
--> src/main.rs:8:5
|
8 | / fn next(&mut self) -> Option<Self::Item> {
9 | | let x = 1;
10 | | let y = 2;
11 | | return Some(&self.string[x .. y]);
12 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:11:22
|
11 | return Some(&self.string[x .. y]);
| ^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 6:6...
--> src/main.rs:6:6
|
6 | impl<'a> Iterator for A<'a> {
| ^^
= note: ...so that the types are compatible:
expected std::iter::Iterator
found std::iter::Iterator
我尝试过:
fn next<'b: 'a>(&'b mut self) -> Option<&'b str> {
//do something to get the index `x` and `y`
return Some(&self.string[x .. y]);
}
编译器说:
error[E0195]: lifetime parameters or bounds on method `next` do not match the trait declaration
--> src/main.rs:8:12
|
8 | fn next<'b: 'a>(&'b mut self) -> Option<&'b str> {
| ^^^^^^^^ lifetimes do not match method in trait