rust - 将泛型类型添加到返回 impl Trait 的函数需要使用“静态生命周期”
问题描述
我有一个将引用作为参数并返回的函数impl Future
。未来不引用参数(它需要一个副本),因此引用不必超过函数调用:
use futures::{Future, future}; // 0.1.25
pub struct Point<'a> {
_name: &'a str,
}
pub fn write<'a>(_points: &'a [Point<'a>]) -> impl Future<Item = (), Error = ()> + 'static {
future::ok(())
}
pub fn call_write(points: Vec<Point>) -> impl Future<Item = (), Error = ()> {
// this works fine
write(&points)
}
我想调整我的write
函数以采用通用参数,但是当我这样做时,编译器认为我的函数'static
不需要生命周期'a
:
pub fn write<'a, T: 'a>(_points: &'a [T]) -> impl Future<Item = (), Error = ()> + 'static {
future::ok(())
}
error[E0621]: explicit lifetime required in the type of `points`
--> src/lib.rs:11:42
|
11 | pub fn call_write(points: Vec<Point>) -> impl Future<Item = (), Error = ()> {
| ---------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ lifetime `'static` required
| |
| help: add explicit lifetime `'static` to the type of `points`: `std::vec::Vec<Point<'static>>`
我的函数与泛型的write
行为没有任何不同,那么为什么编译器认为泛型的参数应该是“静态的”?T
Point
write
返回的未来确实有生命周期'static
,因为它不包含对原始参数的引用。在实际代码中,参数被序列化为 a Vec<u8>
,它归未来所有。
impl Future + 'static
用作品替换Box<dyn Future + 'static>
,所以我在看impl Trait
?
pub fn write<'a, T: 'a>(_points: &'a [T]) -> Box<dyn Future<Item = (), Error = ()> + 'static> {
1.30前后的错误是一样的,所以我认为这一定与impl Trait本身有关,而不是最近生命周期省略的任何变化。在我看来,返回类型正在捕获它不应该捕获的生命周期边界。
解决方案
推荐阅读
- jquery - 调整宽度
用于显示特定数量的行
- java - 我的 android studio 正在我的手机上安装两个应用程序/apk
- powershell - 尝试创建弹出窗口时方法调用失败
- ansible - 受管节点上特定 sudo 命令的 ansible 行为
- python - 如何将不同长度的字符串转换为不同精度的时间戳进行pandas插值?
- javascript - insertBefore javascript,在链接之间添加元素
- unity3d - WebGL Build 后约 5 秒的黑色 Unity 默认对象
- c# - 如何使用 asp.net C# web 表单隐藏 asp 控件
- javascript - 基于由数组组成的对象替换句子中的单词
- python - 如何创建一个可以连续输入金额并以美元显示剩余金额的财务程序