diff --git a/en/src/lifetime/basic.md b/en/src/lifetime/basic.md index 1007af2..b693c72 100644 --- a/en/src/lifetime/basic.md +++ b/en/src/lifetime/basic.md @@ -274,4 +274,85 @@ fn main() } ``` -## elision \ No newline at end of file +## Method +Methods are annotated similarly to functions. + +**Example** +```rust,editable +struct Owner(i32); + +impl Owner { + // Annotate lifetimes as in a standalone function. + fn add_one<'a>(&'a mut self) { self.0 += 1; } + fn print<'a>(&'a self) { + println!("`print`: {}", self.0); + } +} + +fn main() { + let mut owner = Owner(18); + + owner.add_one(); + owner.print(); +} +``` + +9、🌟🌟 +```rust,editable +/* Make it work by adding proper lifetime annotations */ +struct ImportantExcerpt { + part: &str, +} + +impl ImportantExcerpt { + fn level(&'a self) -> i32 { + 3 + } +} + +fn main() {} +``` + +## Elision +Some lifetime patterns are so comman that the borrow checker will allow you to omit them to save typing and to improve readablity. + +This is known as **Elision**. Elision exist in Rust only because these patterns are common. + +For a more comprehensive understanding of elision, please see [lifetime elision](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#lifetime-elision) in the official book. + +10、🌟🌟 +```rust,editable +/* Remove all the lifetimes that can be elided */ + +fn nput<'a>(x: &'a i32) { + println!("`annotated_input`: {}", x); +} + +fn pass<'a>(x: &'a i32) -> &'a i32 { x } + +fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &'a str { + x +} + +struct Owner(i32); + +impl Owner { + // Annotate lifetimes as in a standalone function. + fn add_one<'a>(&'a mut self) { self.0 += 1; } + fn print<'a>(&'a self) { + println!("`print`: {}", self.0); + } +} + +struct Person<'a> { + age: u8, + name: &'a str, +} + +enum Either<'a> { + Num(i32), + Ref(&'a i32), +} + +fn main() {} +``` \ No newline at end of file diff --git a/solutions/lifetime/basic.md b/solutions/lifetime/basic.md index 7c273ab..cf93c0a 100644 --- a/solutions/lifetime/basic.md +++ b/solutions/lifetime/basic.md @@ -192,6 +192,54 @@ fn main() } ``` +9. +```rust +struct ImportantExcerpt<'a> { + part: &'a str, +} + +impl<'a> ImportantExcerpt<'a> { + fn level(&'a self) -> i32 { + 3 + } +} + +fn main() {} +``` +10. +```rust +fn nput(x: &i32) { + println!("`annotated_input`: {}", x); +} + +fn pass(x: &i32) -> &i32 { x } + +fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &'a str { + x +} + +struct Owner(i32); + +impl Owner { + // Annotate lifetimes as in a standalone function. + fn add_one(&mut self) { self.0 += 1; } + fn print(&self) { + println!("`print`: {}", self.0); + } +} + +struct Person<'a> { + age: u8, + name: &'a str, +} + +enum Either<'a> { + Num(i32), + Ref(&'a i32), +} + +fn main() {} +``` \ No newline at end of file