Rust “expected type” error prints mismatched types that are exactly the same

断了今生、忘了曾经 提交于 2020-06-27 09:59:05

问题


With nightly rust:

Playground

struct Foo<T, F: Fn(&T, &T) -> T> {
    value: T,
    func: F
}

fn main() {
    let lambda = |&x, &y| x + y;
    let foo = Foo {
        value: 5 as i32,
        func: lambda
    };
}

Error message:

Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
 --> src/main.rs:8:15
  |
8 |     let foo = Foo {
  |               ^^^ one type is more general than the other
  |
  = note: expected type `std::ops::FnOnce<(&i32, &i32)>`
             found type `std::ops::FnOnce<(&i32, &i32)>`

Note that the expected type and found type are character for character identical. Why is the error message saying that one type is more general than the other, while also saying that they are the same type?


回答1:


With nightly rust:

This appears to be just a "bad" error message in a nightly build. In Rust 1.32 (stable), the errors tell you that this is a lifetime mismatch:

error[E0631]: type mismatch in closure arguments
 --> src/main.rs:8:15
  |
7 |     let lambda = |&x, &y| x + y;
  |                  -------------- found signature of `fn(&_, &_) -> _`
8 |     let foo = Foo {
  |               ^^^ expected signature of `for<'r, 's> fn(&'r i32, &'s i32) -> _`
  |
note: required by `Foo`
 --> src/main.rs:1:1
  |
1 | struct Foo<T, F: Fn(&T, &T) -> T> {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error[E0271]: type mismatch resolving `for<'r, 's> <[closure@src/main.rs:7:18: 7:32] as std::ops::FnOnce<(&'r i32, &'s i32)>>::Output == i32`
 --> src/main.rs:8:15
  |
8 |     let foo = Foo {
  |               ^^^ expected bound lifetime parameter, found concrete lifetime
  |
note: required by `Foo`
 --> src/main.rs:1:1
  |
1 | struct Foo<T, F: Fn(&T, &T) -> T> {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Why is the error message saying that one type is more general than the other, while also saying that they are the same type?

The types differ only in lifetimes. The nightly message doesn't include lifetimes — perhaps in an attempt to reduce noise in cases where the lifetimes are not relevant. Obviously this is not at all helpful when lifetimes are the only difference between the types.

Consider reporting a bug to the Rust team.



来源:https://stackoverflow.com/questions/54341465/rust-expected-type-error-prints-mismatched-types-that-are-exactly-the-same

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!