问题描述
为什么 [1,1] ==& [1,1]
甚至不能编译(可能是因为它们是不同的类型),但是下面的代码片段可以编译并正常运行.
Why would [1,1] == &[1,1]
not even compile (presumably because they're different types), yet the following snippet compiles and runs fine.
let a: [i32; 100] = [1; 100];
let b: &[i32] = &a[1..3];
if b == [1, 1] { // comparison with &[1, 1] works as well
println!("it works"); // this does get printed
}
推荐答案
现在,Rust中的数组有些特殊,因为Rust缺少类型级别的整数.您不能编写函数 fn f< T,N>(array:& [T; N])
.同样,您不能实现在 N
上通用的特征.
Right now, arrays in Rust are somewhat special because Rust lacks type-level integers. You can't write a function fn f<T, N>(array: &[T; N])
. Likewise, you can't implement a trait which is generic over N
.
标准库提供了一些长度范围从0到32的特征实现,以缓解此问题,这就是 b == [1,1]
起作用的原因.对于这种情况,有一个特征 PartialEq
的实现:
The standard library provides some trait implementations for array lengths ranging from 0 to 32 to mitigate this issue, which is why b == [1,1]
works. There's an implementation of the trait PartialEq
for this case:
impl<'a, 'b, A, B> PartialEq<[A; 2]> for &'b [B]
where B: PartialEq<A>
但是,特征 PartialEq<& [A;2]>
未为 [B;2]
.因此,您无法比较 [1,1]
和& [1,1]
. b == [1;33]
在您的示例中也将不起作用,因为没有用于32个以上元素的数组的实现.
However, the trait PartialEq<&[A; 2]>
is not implemented for [B; 2]
. Thus you cannot compare [1, 1]
and &[1, 1]
. b == [1; 33]
will not work in your example too, as there's no implementations for arrays longer than 32 elements.
但是正在努力将类型级别的整数引入Rust. RFC 2000 是最新的建议.
But there's ongoing effort to bring type-level integers into Rust. RFC 2000 is the latest proposal.
目前,您可以依靠从引用到数组到引用到切片的隐式转换.像这样
For the time being you can rely on implicit conversion from reference to the array to reference to slice. Like this
fn f<T>(slice: &[T]) {}
f(&[1, 2, 3, 4]);
这篇关于在Rust中如何将切片与数组进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!