【问题标题】:Expected concrete lifetime, found bound lifetime parameter when storing a fn in a struct预期的具体生命周期,在结构中存储 fn 时找到绑定的生命周期参数
【发布时间】:2016-12-11 14:30:16
【问题描述】:

我正在尝试将函数存储在结构中:

trait T<'a> {}

struct A {}

struct B<'a> {
    a: &'a A
}

impl<'a> T<'a> for B<'a> {}

fn f1<'a, E: T<'a>>(a: &'a A) {}

struct D {
    f: fn(&A)
}

fn main() {
    let d = D { f: f1::<B> };
}

编译器抱怨:

error[E0308]: mismatched types
  --> src/main.rs:18:20
   |
18 |     let d = D { f: f1::<B> };
   |                    ^^^^^^^ expected concrete lifetime, found bound lifetime parameter 
   |
   = note: expected type `fn(&A)`
   = note:    found type `fn(&A) {f1::<'_, B<'_>>}`

【问题讨论】:

    标签: rust


    【解决方案1】:

    当您编写f1::&lt;B&gt; 时,编译器将其解释为f1::&lt;B&lt;'_&gt;&gt;,其中'_ 是编译器推断的生命周期,因为B 在生命周期内是泛型的,您只能将具体类型作为类型参数传递.

    但是,在D 中,f 字段应该是一个函数,它接受对 A 的引用,并且具有任何生命周期。 f1::&lt;B&gt; 不满足该要求,因为该函数已被实例化,具有特定的生命周期。

    不幸的是,目前还没有办法使这项工作正常进行。 Rust 必须支持 higher kinded typesassociated type constructors。然后,您可以将 f1 中的 E 定义为类型构造函数参数,而不是类型参数(尽管我想知道编译器将如何处理 'a 生命周期参数)。

    【讨论】:

    • 我认为你是对的,但这并没有阻止我尝试以几种方式使用for&lt;'a&gt; ... 来绕过它。 :-)
    • 我读过一些关于 for 的文章,但没有找到绕过它的方法。我可以知道你是怎么做到的吗?
    • @Cheng-ChangWu:Chris 的意思是他尝试使用for&lt;'a&gt;... 来解决您的问题,但不幸的是它在这里不起作用。作为记录,在D 中,f: fn(&amp;A)f: for&lt;'a&gt; fn(&amp;'a A) 的简写。
    猜你喜欢
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    相关资源
    最近更新 更多