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

时间:2017-03-03 15:43:53

标签: rust lifetime associated-types

我正在尝试使用一个函数定义一个特征,该函数返回一个与一个参数具有相同生命周期的关联类型。

概念上类似于以下内容(不起作用:lifetime parameter not allowed on this type [Self::Output]):

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

我在Stack Overflow和Internet上找到了关于相关类型生命周期的几个问题,但似乎没有任何帮助。有人建议在整个特征上定义生命周期:

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

但这也不起作用:它编译,但是后面的函数无法编译:

fn f<'a, T>(var: &T)
    where T: Trait<'a>
{
    let input = 0i32;
    let output = var.get_output(&input);
}

给出错误:

error: `input` does not live long enough
  --> <anon>:9:35
   |
   |     let output = var.get_output( &input );
   |                                   ^^^^^ does not live long enough
   | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the body at 7:48...
  --> <anon>:7:49
   |
   |   fn f<'a, T>( var : &T ) where T : Trait<'a> {
   |  _________________________________________________^ starting here...
   | |     let input = 0i32;
   | |     let output = var.get_output( &input );
   | | }
   | |_^ ...ending here

我应该如何定义特征以使其表现得如我所愿?

2 个答案:

答案 0 :(得分:4)

目前这是不可能的,即使是在夜间生锈。

这需要某种形式的高阶类型(HKT),目前设想的方法被称为Associated Type Constructor(ATC)。

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

使用ATC,语法为:

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

注意:如果您想了解ATC,请参阅Niko's series of articles

对于你所拥有的特定例子,你可以使用Shepmaster所指出的HRTB(更高的排名特征界限)解决这个问题:

fn f<T>(var: &T)
    where for<'a> T: Trait<'a>
{ ... }
然而,这是相当有限的(特别是限于特质界限)。

答案 1 :(得分:3)

相关问题