简体   繁体   English

为什么在 Rust 中比较 Vector 和 Array 没有错误?

[英]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.

相关问题 比较单元阵列的内容与向量 - Comparing content of a cell array with a vector 假设元素的顺序不同,将向量与数组进行比较 - Comparing a vector with an array assuming the elements are in different order “错误:下标值既不是数组,也不是指针,也不是矢量”,但是为什么呢? - “error: subscripted value is neither array nor pointer nor vector”, but why? 如何在 Rust 中将一串数字转换为整数数组或向量? - How can I convert a string of numbers to an array or vector of integers in Rust? 比较数组元素的代码中的错误 - error in code comparing elements of an array Rust:向量实现问题 - Rust: vector implementation problems 由于将int []数组与字符串值进行比较,为什么编译器没有给出编译器错误? - Why is the compiler not giving a compiler error since I am comparing int[] array with a string value? 为什么比较对象和对象数组是不同的 - Why comparing objects and array of objects is different 比较Google脚本中的数组元素时出错 - Error comparing Array elements in Google script 为什么 Rust 中的 for 循环可以遍历切片或迭代器,而不是数组? - Why can a for loop in Rust iterate over a slice or iterator, but not an array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM