提问人:Larynx 提问时间:6/8/2022 更新时间:6/8/2022 访问量:529
为什么在 Rust 中比较 Vector 和 Array 没有错误?
Why is there no error comparing Vector and Array in Rust?
问:
我知道 Array 和 Vector 在 Rust 语言中是不同的类型,但我想知道为什么比较两者没有错误。
// Rust Programming Language
fn main() {
let vec = vec!["a", "b", "c"]; // Vector
let arr = ["a", "b", "c"]; // Array
println!("{}", vec == arr); // true!
}
答:
4赞
Chayim Friedman
6/8/2022
#1
因为 Vec<T>
实现了 PartialEq<[T;N]>
,允许您将向量与数组进行比较。
你可以通过实现 PartialEq
trait 来重载 Rust 中的相等运算符,它需要一个(可选,默认为 )泛型参数来允许你为左侧(实现类型)和右侧(泛型参数,默认相同)指定不同的类型。Self
Self
3赞
Dogbert
6/8/2022
#2
运算符适用于实现 PartialEq
特征的任何类型。该特征可以针对左侧和右侧的不同类型实现。在本例中,为所有这些切片类型实现特征:==
Vec<T>
PartialEq<&'_ [U; N]>
PartialEq<&'_ [U]>
PartialEq<&'_ mut [U]>
PartialEq<[U; N]>
PartialEq<[U]>
代码中的数组具有匹配的类型,因此有效。[&str; 3]
[U; N]
评论
PartialEq<[U;N]>
。Vec