Rust 的用途<'lifetime>语法是什么?

问题描述 投票:0回答:1

如果您创建一个返回

impl Trait
的函数,该函数需要无法删除的生命周期,rustc 会告诉您添加它。

use futures::prelude::*;

fn make_fut(input: &()) -> impl Future<Output = ()> {
    async move {
        return *input
    }
}
error[E0700]: hidden type for `impl futures::Future<Output = ()>` captures lifetime that does not appear in bounds
 --> src/lib.rs:4:5
  |
3 |   fn make_fut(input: &()) -> impl Future<Output = ()> {
  |                      ---     ------------------------ opaque type defined here
  |                      |
  |                      hidden type `{async block@src/lib.rs:4:5: 4:15}` captures the anonymous lifetime defined here
4 | /     async move {
5 | |         return *input
6 | |     }
  | |_____^
  |
help: add a `use<...>` bound to explicitly capture `'_`
  |
3 | fn make_fut(input: &()) -> impl Future<Output = ()> + use<'_> {
  |                                                     +++++++++

For more information about this error, try `rustc --explain E0700`.

这个错误可以通过简单地将

+ '_
添加到返回类型来修复,但 rustc 告诉使用者添加
+ use<'_>
来代替。运行
rustc --explain E0700
仅显示之前的更改,根本不提及
use<'_>
Rust book 没有提及在此上下文中使用
use

这个

use<'lifetime>
语法是什么? 它在哪里记录?我如何了解何时应该使用它而不是其他语法?

rust
1个回答
0
投票

这是一个新语法,在 Rust 1.82.0 中发布。

在发布博客文章中,我们可以找到更多有关它的信息,并且还有专门针对此语法(及其兄弟)的博客文章,但大多数信息可以在RFC中找到。

简而言之,

use<'lifetime>
+ 'lifetime
的替代品,但更清晰、更好用——在某些情况下,特别是那些涉及多个生命周期和有边界的生命周期的情况下,
+ 'lifetime
不会起作用,但
use<'lifetime>
会起作用(如RFC 中有解释)。

未来它还将支持

use<Type>
(意思是“捕获
Type
中的所有生命周期),这不能使用
+
语法来表达(尽管也不需要,因为默认的过去(现在仍然)捕获所有类型)。

但最重要的是,它允许您选择out捕获:自 2024 版以来(甚至在此之前,特征中返回类型中的

impl Trait
),默认情况下所有类型和生命周期都将是捕获(以前,仅类型被捕获)。
use<[optionally capture only some]>
允许您在需要时恢复旧的行为。

请注意,截至撰写本文时,RFC 尚未完全实现:目前,您仍然必须捕获所有类型,并且我相信在特征中使用

use
刚刚实现(甚至可能尚未合并)。这些限制最终将被取消。

© www.soinside.com 2019 - 2024. All rights reserved.