I know that Array and Vector are different types in Rust language, but I wonder why there is no error in comparing the two.
// Rust Programming Language
fn main() {
let vec = vec!["a", "b", "c"]; // Vector
let arr = ["a", "b", "c"]; // Array
println!("{}", vec == arr); // true!
}
CodePudding user response:
Because Vec<T>
implements PartialEq<[T; N]>
, allowing you to compare vectors with array.
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).
CodePudding user response:
The ==
operator works on any type that implements the PartialEq
trait. 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:
PartialEq<&'_ [U; N]>
PartialEq<&'_ [U]>
PartialEq<&'_ mut [U]>
PartialEq<[U; N]>
PartialEq<[U]>
The array in your code has the type [&str; 3]
, which matches [U; N]
and therefore this works.