本文介绍了为什么不能将借用的整数与文字整数进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取条件为真的数组中的元素.例如.我想要数组元素为 0 的所有索引:

I want to get the elements in an array where a condition is true. For example. I would like all indices where the array elements are 0:

fn main() {
    let lim = 10;
    let mut sieve = vec![0; lim + 1];
    sieve[1] = 1;
    println!(
        "{:?}",
        sieve
            .iter()
            .enumerate()
            .filter(|&(_, c)| c != 0)
            .map(|(i, _)| i)
            .collect::<Vec<usize>>()
    );
}

但这是一个编译错误:

error[E0277]: can't compare `&{integer}` with `{integer}`
  --> src/main.rs:10:33
   |
10 |             .filter(|&(_, c)| c != 0)
   |                                 ^^ no implementation for `&{integer} == {integer}`
   |
   = help: the trait `std::cmp::PartialEq<{integer}>` is not implemented for `&{integer}`

当我使用 c.clone() != 0 它可以工作.

When I use c.clone() != 0 it works.

如果我正确理解了错误消息,Rust 会抱怨它无法将借用与带有整数的整数进行比较.我不明白为什么这不可能.

If I understand the error message correctly, Rust complains that it can't compare a borrow to an integer with an integer. I don't see why it shouldn't be possible.

推荐答案

您正确解释了错误,原因是它根本没有实现.如果标准库编写者想要完成这项工作,他们必须为 &i32 == i32, i32 == &i32PartialEq/code>, &mut i32 == i32, i32 == &mut i32, &i32 == &mut i32&mut i32 == &i32.然后他们必须对所有其他原始类型(i8i16u8u16u32i64u64f32f64字符).

You interpret the error correctly, and the reason is that it simply isn't implemented. If the standard library writers wanted to make this work, they'd have to implement PartialEq for &i32 == i32, i32 == &i32, &mut i32 == i32, i32 == &mut i32, &i32 == &mut i32 and &mut i32 == &i32. And then they'd have to do that for all other primitive types (i8, i16, u8, u16, u32, i64, u64, f32, f64, and char).

这是很多PartialEq实现.

或者,他们可以要求语言的用户编写 *c != 0.

Or instead they can just ask the users of the language to write *c != 0.

(如果您来自 C++,要理解的关键是在语法上,借用更像是指针而不是引用.只有方法调用语法具有自动取消引用功能.)

(If you're coming from C++, the key thing to understand is that syntactically, borrows are more like pointers than references. Only method call syntax has the auto-deref feature.)

这篇关于为什么不能将借用的整数与文字整数进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 23:05