目录
当前位置: 首页 > 文档资料 > 通过例子学 Rust >

生命周期 - 省略

优质
小牛编辑
127浏览
2023-12-01

有些生命周期的模式太过普遍了,所以借用检查器将会隐式地添加它们来以减少字母输入和增强可读性。这种隐式添加生命周期的过程称为省略(elision)。在 Rust 使用省略仅仅是因为这些模式太普遍了。

下面代码展示了一些省略的例子。对于省略的详细描述,可以参考官方文档的 生命周期省略

  1. // `elided_input` 和 `annotated_input` 本质上拥有相同的识别标志,是因为
  2. // `elided_input` 的生命周期被编译器省略掉了:
  3. fn elided_input(x: &i32) {
  4. println!("`elided_input`: {}", x)
  5. }
  6. fn annotated_input<'a>(x: &'a i32) {
  7. println!("`annotated_input`: {}", x)
  8. }
  9. // 类似地,`elided_pass` 和 `annotated_pass` 也拥有相同的识别标志,
  10. // 是因为生命周期被隐式地添加进 `elided_pass`:
  11. fn elided_pass(x: &i32) -> &i32 { x }
  12. fn annotated_pass<'a>(x: &'a i32) -> &'a i32 { x }
  13. fn main() {
  14. let x = 3;
  15. elided_input(&x);
  16. annotated_input(&x);
  17. println!("`elided_pass`: {}", elided_pass(&x));
  18. println!("`annotated_pass`: {}", annotated_pass(&x));
  19. }

参见:

省略