【问题标题】:Why does rustc say the inferred types mismatched? [duplicate]为什么 rustc 说推断的类型不匹配? [复制]
【发布时间】:2021-06-12 22:14:43
【问题描述】:

如果我尝试创建一个函数指针向量,编译器总是抱怨错误的类型(尽管我没有明确声明任何类型):

fn abc() {}

fn def() {}

fn main()
{
    let a = vec![abc, def];
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ef52fe778db1112433d20dd02b3d0b54

error[E0308]: mismatched types
 --> src/main.rs:5:13
  |
5 |     let a = vec![abc, def];
  |             ^^^^^^^^^^^^^^ expected slice, found array of 2 elements
  |
  = note: expected struct `Box<[fn() {abc}], _>`
             found struct `Box<[fn(); 2], std::alloc::Global>`
  = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `tes`

To learn more, run the command again with --verbose.

【问题讨论】:

    标签: types rust typeerror type-inference


    【解决方案1】:

    我相信 Rust 试图为函数赋予唯一的类型,所以只需指定它是一个函数指针 Vec。这也避免了Box&lt;dyn Fn()&gt;的额外间接和分配:

    fn abc() {}
    fn def() {}
    
    fn main() {
        let a: Vec<fn()> = vec![abc, def];
    }
    

    或者,可以推断“投射”第一个和其余的:

    fn abc() {}
    fn def() {}
    
    fn main() {
        let a = vec![abc as fn(), def];
    }
    

    【讨论】:

    • 小修正:它避免了额外的分配,但仍然有一定程度的间接性(“函数指针”的“指针”部分)。虽然可以说它仍然是 less 间接,因为您不必同时遵循 vtable 指针 函数指针。
    【解决方案2】:

    这两个函数有不同的类型,你应该能够显式地Box它们并转换为Box&lt;dyn Fn()&gt;

    fn abc() {}
    fn def() {}
    fn main()
    {
        let a = vec![Box::new(abc) as Box<dyn Fn()>, Box::new(def) as Box<dyn Fn()>];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 2021-09-15
      • 2020-04-24
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多