比较平等与参数的&和*的变化有什么区别?

问题描述 投票:0回答:1

我写了以下函数:

fn test() {
    let xs = [b"AAA", b"BBB"];
    let buf = b"AAA";
    println!("{:?}", xs.iter().find(|&x| &x == &&buf));
}

这有效,但我很困惑,因为这些也有效:

  • println!("{:?}", xs.iter().find(|&x| x == &buf));
  • println!("{:?}", xs.iter().find(|&x| *x == buf));

这些变化有什么区别? *&的行为肯定与C中的行为完全不同。我需要了解这些算子的细微差别才能理解上述内容?

pointers rust
1个回答
1
投票

相关差异在于等式运算符的行为。 x == y&x == &y的语义是相同的:他们比较xy

&x == &y desugars to PartialEq::eq(&&x, &&y)PartialEq反过来有全面实施

impl<'a, 'b, A, B> PartialEq<&'b B> for &'a A
where
    A: PartialEq<B> + ?Sized,
    B: ?Sized,

它写着“如果AB类型的值可以进行相等性比较(where A: PartialEq<B>),那么我们提供了一个实现,用于比较&A&Bimpl PartialEq<&B> for &A)类型的值。”我为了简洁省略了生命。

实现是straightforward,它比较了解除引用的值。

fn eq(&self, other: & &'b B) -> bool { 
    PartialEq::eq(*self, *other) 
}

因此PartialEq::eq(&&x, &&y)PartialEq::eq(*&&x, *&&y),与PartialEq::eq(&x, &y)x == y相同。

© www.soinside.com 2019 - 2024. All rights reserved.