繁体   English   中英

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

[英]Define a trait with a function that returns an associated type with the same lifetime as one parameter

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

概念上类似于以下内容(这不起作用: 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

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

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

这需要某种形式的高级类型(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的系列文章


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

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

然而,这是相当有限的(特别是,限于特质界限)。

这需要使用排名较高的特征界限

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

也可以看看:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM