【问题标题】:mismatched types between method and lifetime-generic parameter方法和生命周期通用参数之间的类型不匹配
【发布时间】:2022-08-22 00:29:11
【问题描述】:

我希望以下 Rust 代码能够工作

struct Expression<\'a> {
    s: &\'a str,
}

impl<\'a> Expression<\'a> {
    fn foo(e: Expression<\'a>, _: Expression<\'a>) -> Expression<\'a> {
        e
    }
}

fn accept(_: for<\'a> fn(Expression<\'a>, Expression<\'a>) -> Expression<\'a>) {
    
}

fn main() {
    accept(Expression::foo)
}

但我收到一条错误消息:

error[E0308]: mismatched types
  --> src/main.rs:16:12
   |
16 |     accept(Expression::foo)
   |            ^^^^^^^^^^^^^^^ one type is more general than the other
   |
   = note: expected fn pointer `for<\'a> fn(Expression<\'a>, Expression<\'a>) -> Expression<\'a>`
              found fn pointer `fn(Expression<\'_>, Expression<\'_>) -> Expression<\'_>`

For more information about this error, try `rustc --explain E0308`.

可以通过引入另一个生命周期来修复错误\'b

impl<\'a> Expression<\'a> {
    fn foo<\'b>(e: Expression<\'b>, _: Expression<\'b>) -> Expression<\'b> {
        e
    }
}

有人可以向我解释为什么这是必要的吗? \'a 不是已经通用了吗?

    标签: rust types lifetime


    【解决方案1】:

    late-bound vs. early-bound 生命周期的另一个实例。

    Using HRTBs to automate getter method unit tests 也有类似的问题。问题是,虽然 foo'a 通用,但它不是后期绑定早绑定,这意味着当我们指定函数的名称时它是固定的,我们不能从中创建通用函数指针 (for&lt;'a&gt;)。

    【讨论】:

    • 知道这一点非常有用。如果foo 接受并返回self 而不是e,这根本就不能挽救吗?
    • 我想你可以在self 的整个生命周期内使accept 通用,没关系。
    • @isaactfa 它可以关闭,就像在链接的问题中一样。
    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2016-01-29
    • 2011-04-16
    • 2019-04-08
    • 1970-01-01
    相关资源
    最近更新 更多