在字符串切片数组中查找字符串切片

Finding string slices in an array of string slices

我有一大堆静态分配的字符串切片,定义如下:

const ARR: [&'static str; 50] = [...];

然后我以正常方式遍历数组(我是 Rust 的新手):

for el in ARR.iter() {
    if el == target {
        return true;
    }
}

不幸的是,当我尝试使用 eq():

时出现错误
error: the trait `core::cmp::PartialEq<str>` is not implemented for the type `&str`

标准库中是否有比较字符串切片的东西,还是我必须自己遍历并比较字符?而且,就此而言,是否有比我正在做的更好的方法来搜索数组中的元素?

谢谢!

以下是编写示例的方法:

const FRUITS: [&'static str; 3] = ["apple", "banana", "coconut"];

fn is_available(desired: &str) -> bool {
    for &el in FRUITS.iter() {
        // let () = el; // PROTIP
        if el == desired {
          return true;
        }
    }

    false
}

看到我在哪里将 el 分配给 () 了吗?这是在某个时候查看变量类型的小技巧。如果您取消注释,您将收到如下错误:

error: mismatched types:
 expected `&&str`,
    found `()`

这让您知道类型是什么。第二部分是查看 PartialEqstr 的实现,重要的是:

impl PartialEq<str> for str 

因此我们将 el 绑定到一个模式,该模式将自动为我们取消引用一次。然后可以进行比较,因为我们有平衡数量的取消引用要做:

for &el in FRUITS.iter() {
//  ^~~ Here

但实际上,我会这样写:

static FRUITS: [&'static str; 3] = ["apple", "banana", "coconut"];

fn main() {
    let desired = "apple";
    let to_eat = FRUITS.iter().find(|&&f| f == desired);
    println!("{:?}", to_eat);

    let desired = "durian";
    let to_eat = FRUITS.iter().find(|&&f| f == desired);
    println!("{:?}", to_eat);
}

static 在内存中为变量创建一个实际的共享位置。 const 的行为更像 C #define - 该值被插入到任何使用它的地方。由于 find returns 项目,我们需要它有一些比 one 表达式持续时间更长的存储空间。

IteratorExt::find also abstracts the work of finding a matching value (for some condition), and returns an Option表示成功/失败。