我有一大堆静态分配的字符串切片,定义如下:
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 `()`
这让您知道类型是什么。第二部分是查看 PartialEq
对 str
的实现,重要的是:
impl PartialEq<str> for str
因此我们将 el
绑定(bind)到一个模式,该模式将自动为我们解除引用一次。然后可以进行比较,因为我们有平衡数量的取消引用要做:
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
返回项目,我们需要它有一些比 one 表达式持续时间更长的存储空间。
IteratorExt::find
还抽象了寻找匹配值的工作(对于某些条件),并返回 Option
表示成功/失败。
关于rust - 在字符串切片数组中查找字符串切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29243469/