following code带有完整的类型注释:
fn enter<'a, F, R>(x: &'a i32, func: F) -> R
where
F: for<'b> FnOnce(&'b i32) -> R,
{
func(x)
}
fn identity<'a>(x: &'a i32) -> &'a i32 {
x
}
fn main() {
let x = &42;
enter(x, identity);
}
编译器在编译时报告错误:
error[E0308]: mismatched types
--> src/main.rs:14:5
|
14 | enter(x, identity);
| ^^^^^^^^^^^^^^^^^^ one type is more general than the other
|
= note: expected trait `for<'b> FnOnce<(&'b i32,)>`
found trait `for<'a> FnOnce<(&'a i32,)>`
note: the lifetime requirement is introduced here
--> src/main.rs:3:35
|
3 | F: for<'b> FnOnce(&'b i32) -> R,
| ^
For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error
我的理解是,性状界限for<'b> FnOnce(&'b i32) -> R
比identity
的签名for<'a> fn(&'a i32) -> &'a i32
更一般,所以它应该通过.
然而,通用-> R
似乎是停止编译的罪魁祸首,但我不知道为什么.
我注意到有类似的问题,但他们遇到了错误,因为他们的类型没有完全注释,编译器错误地推断了类型.
相关:
- Rust "expected type" error prints mismatched types that are exactly the same个
- One type (function pointer) is more general than the other个
- "one type is more general than the other" error in Rust while types are identical个
- Creating an alias for a Fn trait results in "one type is more general than the other" error个
- https://users.rust-lang.org/t/solved-one-type-is-more-general-than-the-other-but-they-are-exactly-the-same/25194个