在返回位置具有泛型关联类型的 Impl 特征导致生命周期错误 [英] Impl trait with generic associated type in return position causes lifetime error

查看:29
本文介绍了在返回位置具有泛型关联类型的 Impl 特征导致生命周期错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要存储一个 fn(I) ->'static 结构中的 O(其中 I & O 可以是引用).O 需要是具有 'static 泛型关联类型的特征,该关联类型也存储在结构中.IO 本身都不会存储在结构体中,因此它们的生命周期无关紧要.但是编译器仍然抱怨 I 活得不够久.

I need to store a fn(I) -> O (where I & O can be references) in a 'static struct. O needs to be a trait with an 'static generic associated type, that associated type is also stored in the struct. Neither I nor O itself get stored inside of the struct, so their lifetime shouldn't matter. But the compiler is still complaining about I not living long enough.

trait IntoState {
    type State: 'static;

    fn into_state(self) -> Self::State;
}

impl IntoState for &str {
    type State = String;

    fn into_state(self) -> Self::State {
        self.to_string()
    }
}

struct Container<F, S> {
    func: F,
    state: S,
}

impl<I, O> Container<fn(I) -> O, O::State>
where
    O: IntoState,
{
    fn new(input: I, func: fn(I) -> O) -> Self {
        // I & O lives only in the next line of code. O gets converted into
        // a `'static` (`String`), that is stored in `Container`.
        let state = func(input).into_state();
        Container { func, state }
    }
}

fn map(i: &str) -> impl '_ + IntoState {
    i
}

fn main() {
    let _ = {
        // create a temporary value
        let s = "foo".to_string();

        // the temporary actually only needs to live in `new`. It is
        // never stored in `Container`.
        Container::new(s.as_str(), map)
        // ERR:        ^ borrowed value does not live long enough
    };
    // ERR: `s` dropped here while still borrowed
}

游乐场

推荐答案

据我所知,编译器的错误信息具有误导性,它实际需要的是显式定义的关联类型:

As far as I can tell, the compiler's error message is misleading, what it actually requires is an explicitly defined associated type:

fn map(i: &str) -> impl '_ + IntoState<State = String> {
    i
}

对问题给出的优秀答案:为什么编译器不推断 impl trait 返回值的关联类型的具体类型? 提供了足够的信息,说明为什么需要这样做.

The excellent answer given to the quesion: Why does the compiler not infer the concrete type of an associated type of an impl trait return value? provides enough information on why this is actually needed.

另见 Rust 问题 #42940 - impl-trait 返回类型受所有输入限制类型参数,即使是不必要的

您可以使用泛型类型参数而不是返回 impl,在这种情况下,您不必指定关联类型:

You can use a generic type parameter instead of returning an impl in which case you don't have to specify the associated type:

fn map<T: IntoState>(i: T) -> T {
    i
}

这篇关于在返回位置具有泛型关联类型的 Impl 特征导致生命周期错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆