[fn] 与 [(fn, u8)] 在类型推断方面有什么区别?

问题描述 投票:0回答:1

为什么会编译:

fn main() {
   let xs = [||1, ||2, ||3];
}

但是这个没有?

fn main() {
   let xs = [(||1, 1), (||2, 2), (||3, 3)];
}
error[E0308]: mismatched types
 --> src/main.rs:2:29
  |
2 |     let xs = [((|| 1), 1), ((|| 2), 2), ((|| 3), 3)];
  |                 --          ^^^^^^ expected closure, found a different closure
  |                 |
  |                 the expected closure
  |
  = note: expected closure `{closure@src/main.rs:2:17: 2:19}`
             found closure `{closure@src/main.rs:2:30: 2:32}`
  = note: no two closures, even if identical, have the same type
  = help: consider boxing your closure and/or using it as a trait object

error[E0308]: mismatched types
 --> src/main.rs:2:42
  |
2 |     let xs = [((|| 1), 1), ((|| 2), 2), ((|| 3), 3)];
  |                 -- the expected closure  ^^^^^^ expected closure, found a different closure
  |
  = note: expected closure `{closure@src/main.rs:2:17: 2:19}`
             found closure `{closure@src/main.rs:2:43: 2:45}`
  = note: no two closures, even if identical, have the same type
  = help: consider boxing your closure and/or using it as a trait object

需要明确的是,问题不是为什么它不能编译这两者之间有什么区别,第一个可以编译,但第二个却不能?.

rust type-inference
1个回答
18
投票

第一种情况是编译器中的特殊情况:当某些类型需要统一时(例如当它们都是同一个数组的元素时),并且它们都是非捕获闭包时,编译器会自动强制它们起作用指针。但是,如果它们是包含非捕获闭包的元组,则这不起作用。

rustc 中的相关代码在这里,如果你感兴趣的话。

© www.soinside.com 2019 - 2024. All rights reserved.