我有一大堆静态分配的字符串切片,定义如下:
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`
标准库中是否存在比较字符串切片的内容,或者我是否必须自己迭代并比较字符?而且,就此而言,是否有更好的方法来搜索数组中的元素而不是我正在做的事情?
谢谢!
答案 0 :(得分:1)
以下是您编写示例的方法:
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 `()`
这可以让您知道类型是什么。第二部分是查看PartialEq
str
的实现,重要的是:
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
会返回该项,因此我们需要一些存储时间超过一个表达式。
IteratorExt::find
也抽象查找匹配值(对于某些条件)的工作,并返回表示成功/失败的Option
。