首页 > 解决方案 > 将泛型类型添加到返回 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行为没有任何不同,那么为什么编译器认为泛型的参数应该是“静态的”?TPointwrite

游乐场链接

返回的未来确实有生命周期'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本身有关,而不是最近生命周期省略的任何变化。在我看来,返回类型正在捕获它不应该捕获的生命周期边界。

标签: rusttraitslifetime

解决方案


推荐阅读