[英]Why is there no error comparing Vector and Array in Rust?
I know that Array and Vector are different types in Rust language, but I wonder why there is no error in comparing the two.我知道 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!
}
Because Vec<T>
implements PartialEq<[T; N]>
因为
Vec<T>
实现PartialEq<[T; N]>
PartialEq<[T; N]>
, allowing you to compare vectors with array. PartialEq<[T; N]>
,允许您将向量与数组进行比较。
You can overload the equality operators in Rust by implementing the PartialEq
trait, and it takes an (optional, defaulted to Self
) generic parameter to allow you to specify different type for the left side ( Self
, the implementing type) and the right side (the generic parameter, by default the same).您可以通过实现
PartialEq
trait 来重载 Rust 中的相等运算符,它需要一个(可选,默认为Self
)泛型参数来允许您为左侧( Self
,实现类型)和右侧(泛型参数,默认相同)。
The ==
operator works on any type that implements the PartialEq
trait. ==
运算符适用于实现PartialEq
特征的任何类型。 The trait can be implemented for different types for the left and the right side.可以为左侧和右侧的不同类型实现特征。 In this case,
Vec<T>
implements the trait for all of these slice types :在这种情况下,
Vec<T>
实现了所有这些切片类型的特征:
PartialEq<&'_ [U; N]>
PartialEq<&'_ [U]>
PartialEq<&'_ mut [U]>
PartialEq<[U; N]>
PartialEq<[U]>
The array in your code has the type [&str; 3]
代码中的数组类型为
[&str; 3]
[&str; 3]
, which matches [U; N]
[&str; 3]
,匹配[U; N]
[U; N]
and therefore this works. [U; N]
,因此这是有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.