省略
有些生命周期的模式太过普遍了,所以借用检查器将会隐式地添加它们来以减少字母输入和增强可读性。这种隐式添加生命周期的过程称为省略(elision)。在 Rust 使用省略仅仅是因为这些模式太普遍了。
下面代码展示了一些省略的例子。对于省略的详细描述,可以参考官方文档的 生命周期省略。
1. // `elided_input` 和 `annotated_input` 本质上拥有相同的识别标志,是因为
2. // `elided_input` 的生命周期被编译器省略掉了:
3. fn elided_input(x: &i32) {
4. println!("`elided_input`: {}", x)
5. }
7. fn annotated_input<'a>(x: &'a i32) {
8. println!("`annotated_input`: {}", x)
9. }
11. // 类似地,`elided_pass` 和 `annotated_pass` 也拥有相同的识别标志,
12. // 是因为生命周期被隐式地添加进 `elided_pass`:
13. fn elided_pass(x: &i32) -> &i32 { x }
15. fn annotated_pass<'a>(x: &'a i32) -> &'a i32 { x }
17. fn main() {
18. let x = 3;
20. elided_input(&x);
21. annotated_input(&x);
23. println!("`elided_pass`: {}", elided_pass(&x));
24. println!("`annotated_pass`: {}", annotated_pass(&x));
25. }
