Here's how you can get rid of false errors. I am new to Rust, so serious errors may occur in the following explanation.
use std::str::Chars; struct A<'a> { chars: Chars<'a>, }
'a Here is the life parameter (as well as the template parameters in C ++). Types can be parameterized by the lifetime in Rust.
The Chars type also takes a lifetime parameter. This implies that the Chars type probably has a member element that requires the lifetime parameter. The lifetime parameters are meaningful only in links (since the lifetime here means "borrowing life").
We know that Chars needs to keep a reference to the line from which it was created, 'a will probably be used to indicate the lifetime of the original line.
Here, we simply supply 'a as a parameter to the Chars lifetime, telling the Rust compiler that the lifetime of the Chars same as the lifetime of struct A The lifetime of the IMO "a type A" should be read as the "lifetime" of the references contained in structure A ".
I think that the implementation of the structure can be parameterized regardless of the structure itself, so we need to repeat the parameters using the impl . Here we bind the name 'a to the lifetime of structure A.
impl<'a> A<'a> {
The name 'b is entered in the context of the function f2 . Here it is used to bind the &mut self link over time.
fn f2<'b>(&'b mut self) {}
The name 'b is entered in the context of the function f1 . This 'b not directly related to 'b introduced above f2 .
Here it is used to bind the &mut self link over time. Needless to say, this link also has nothing to do with &mut self in the previous function, this is a new independent self loan.
If we had not used the explicit annotation of life expectancy, here Rust would have used its rules for eliminating life to get the next signature of the function ...
As you can see, this binds the lifetime of the &mut self reference parameter to the lifetime of the Chars object returned from this function (this Chars object should not be the same as self.chars ), this is absurd, since the returned Chars will survive the &mut self link . Therefore, we need to separate the two lifetimes as follows:
fn f1<'b>(&'b mut self) -> Option<Chars<'a>> { self.chars.next();
Remember &mut self is a loan self , and all that &mut self is mentioned is also a loan. Therefore, we cannot return Some(self.chars) here. self.chars not ours to give (Error: cannot exit borrowed content.).
We need to create a self.chars clone self.chars that it can be issued.
Some(self.chars.clone())
Note that the returned Chars has the same lifetime as structure A.
And now f3 without changes and without compilation errors!
fn f3<'b>(&'b mut self) { if let Some(x) = self.f1() { //This is ok now } else { self.f2() //This is also ok now } }
The main function is for completeness only ...
fn main() { let mut a = A { chars:"abc".chars() }; a.f3(); for c in a.chars { print!("{}", c); } }
I updated the code to make life expectancy relationships clearer.