预期的具体生命周期,在结构中存储 fn 时找到绑定的生命周期参数 [英] Expected concrete lifetime, found bound lifetime parameter when storing a fn in a struct

查看:49
本文介绍了预期的具体生命周期,在结构中存储 fn 时找到绑定的生命周期参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to store a function in a struct:

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<'_>>}`

推荐答案

当您编写 f1::<B> 时,编译器会将其解释为 f1::<B<'_>>,有 '_ 是编译器推断的生命周期,因为 B 在生命周期内是通用的,您只能将具体类型作为类型参数.

When you write f1::<B>, the compiler interprets that as f1::<B<'_>>, there '_ is a lifetime inferred by the compiler, because B is generic over a lifetime and you can only pass concrete types as type parameters.

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

But then, in D, the f field is expected to be a function that accepts references to A with any lifetime. f1::<B> does not fulfill that requirement, because the function has been instantiated with a specific lifetime.

不幸的是,目前还没有办法让这项工作发挥作用.Rust 必须支持 更高级的类型关联类型构造函数.然后,您可以将 f1 中的 E 定义为类型构造函数参数,而不是类型参数(尽管我想知道编译器将如何处理 'a 生命周期参数).

Unfortunately, at the moment, there's no way to make this work. Rust would have to support either higher kinded types or associated type constructors. You could then define E in f1 to be a type constructor parameter, rather than a type parameter (though I'm wondering how the compiler would handle the 'a lifetime parameter).

这篇关于预期的具体生命周期,在结构中存储 fn 时找到绑定的生命周期参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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