为什么泛型的推断不是"transitive"?
Why is the inference of a generic type not "transitive"?
当我尝试编译这段代码时:
use std::borrow::Borrow;
fn test_eq<T, U, B>(t: T, u: U) -> bool
where
T: Borrow<B>,
U: Borrow<B>,
B: PartialEq<B> + ?Sized,
{
t.borrow() == u.borrow()
}
fn main() {
let my_vec = vec![1, 2, 3];
assert!(test_eq(my_vec, [1, 2, 3]));
}
我得到:
error[E0283]: type annotations required: cannot resolve `std::vec::Vec<i32>: std::borrow::Borrow<_>`
--> src/main.rs:15:13
|
15 | assert!(test_eq(my_vec, [1, 2, 3]));
| ^^^^^^^
|
显然,[T]
是 B
的理想候选者,因为:
Vec<T>
实施 Borrow<[T]>
[T, 3]
实施 Borrow<[T]>
[T]
实施 PartialEq<[T]>
如果我明确指定类型,我的代码会编译:
assert!(test_eq::<Vec<i32>, [i32; 3], [i32]>(my_vec, [1, 2, 3]));
为什么这段代码编译失败?
E0283
This error occurs when the compiler doesn't have enough information to unambiguously choose an implementation.
在此示例中,编译器无法推断出 B
是切片类型 [T]
,您至少必须使用注释 [_]
指定该信息:
assert!(test_eq::<_, _, [_]>(my_vec, [1, 2, 3] ));
当我尝试编译这段代码时:
use std::borrow::Borrow;
fn test_eq<T, U, B>(t: T, u: U) -> bool
where
T: Borrow<B>,
U: Borrow<B>,
B: PartialEq<B> + ?Sized,
{
t.borrow() == u.borrow()
}
fn main() {
let my_vec = vec![1, 2, 3];
assert!(test_eq(my_vec, [1, 2, 3]));
}
我得到:
error[E0283]: type annotations required: cannot resolve `std::vec::Vec<i32>: std::borrow::Borrow<_>`
--> src/main.rs:15:13
|
15 | assert!(test_eq(my_vec, [1, 2, 3]));
| ^^^^^^^
|
显然,[T]
是 B
的理想候选者,因为:
Vec<T>
实施Borrow<[T]>
[T, 3]
实施Borrow<[T]>
[T]
实施PartialEq<[T]>
如果我明确指定类型,我的代码会编译:
assert!(test_eq::<Vec<i32>, [i32; 3], [i32]>(my_vec, [1, 2, 3]));
为什么这段代码编译失败?
E0283
This error occurs when the compiler doesn't have enough information to unambiguously choose an implementation.
在此示例中,编译器无法推断出 B
是切片类型 [T]
,您至少必须使用注释 [_]
指定该信息:
assert!(test_eq::<_, _, [_]>(my_vec, [1, 2, 3] ));