update lifetime/basic.md

This commit is contained in:
sunface 2022-03-28 22:02:07 +08:00
parent 1fa2243ede
commit 9b9a981254
2 changed files with 130 additions and 1 deletions

View File

@ -274,4 +274,85 @@ fn main()
}
```
## elision
## 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() {}
```

View File

@ -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() {}
```