在一个字符串数组中检测 Rust 字符串是否包含

5

我是一个Rust初学者,正在尝试将当前用于测试字符串相等性的条件扩展到另一个字符串字面值,以便测试现在是是否包含在字符串字面值数组中。

在Python中,我只需要写string_to_test in ['foo','bar']。 我如何将其移植到Rust?

这是我的尝试,但无法编译:

fn main() {
  let test_string = "foo";
  ["foo", "bar"].iter().any(|s| s == test_string);
}

有错误:

   Compiling playground v0.0.1 (/playground)
error[E0277]: can't compare `&str` with `str`
 --> src/main.rs:3:35
  |
3 |   ["foo", "bar"].iter().any(|s| s == test_string);
  |                                   ^^ no implementation for `&str == str`
  |
  = help: the trait `PartialEq<str>` is not implemented for `&str`
  = note: required because of the requirements on the impl of `PartialEq<&str>` for `&&str`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to previous error

很遗憾我无法理解这个问题,也没有在StackOverflow或论坛上找到类似的问题。

1个回答

14

Herohtar 提出了通用的解决方案:

["foo", "bar"].contains(&test_string) 

PitaJ在评论中提出了这个简洁的宏,这只适用于在编译时已知的令牌,正如Finomnis在评论中指出的:

matches!(test_string, "foo" | "bar")

这是我使我的代码生效的方法:
["foo", "bar"].iter().any(|&s| s == test_string);

7
["foo", "bar"].contains(&test_string) 这样写也完全没问题。 - Herohtar
这是一个更为通用的解决方案,因为闭包可以使用任何返回布尔值的代码,例如 ends_with(s) 等等。 - bmacnaughton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接