且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用函数定义特征,该函数返回与一个参数具有相同生存期的关联类型

更新时间:2022-04-14 03:56:20

即使在夜间Rust中,这目前也是不可能的.

This is currently impossible, even in nightly Rust.

这需要某种形式的高级类型(HKT),目前设想的方法称为关联类型构造函数(ATC).

This requires some form of Higher Kinded Types (HKT), and the current approach envisaged is dubbed Associated Type Constructor (ATC).

引入ATC的主要动机实际上就是这个用例.

The main motivation for introducing ATC is actually this very usecase.

使用ATC时,语法为:

With ATC, the syntax would be:

trait Trait {
    type Output<'a>;
    fn get_output<'a>(&self, input: &'a i32) -> Self::Output<'a>;
}

注意:如果您想了解ATC,请参阅对于您所拥有的特定示例,您可以使用Shepmaster指出的HRTB(较高级别的特质边界)来解决此问题:

For the particular example you have, you can work around this with HRTB (Higher Ranked Traits Bounds) as noted by Shepmaster:

fn f<T>(var: &T)
    where for<'a> T: Trait<'a>
{ ... }

但是这是相当有限的(特别是仅限于特征范围).

however this is fairly limited (notably, limited to trait bounds).