测试 Rust 字符串是否包含在字符串数组中

Cor*_*mer 5 arrays string contains rust

我是 Rust 初学者,我正在尝试扩展当前测试字符串与另一个字符串文字是否相等的条件,以便现在测试该字符串是否包含在字符串文字数组中。

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

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

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

有错误:

   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
Run Code Online (Sandbox Code Playgroud)

不幸的是,我无法弄清楚这一点,并且在 StackOverflow 或论坛上找不到类似的问题。

Cor*_*mer 14

Herohtar提出了一般解决方案:

["foo", "bar"].contains(&test_string) 
Run Code Online (Sandbox Code Playgroud)

PitaJ在评论中建议了这个简洁的宏,这只适用于编译时已知的标记,正如Finomnis在评论中指出的那样:

matches!(test_string, "foo" | "bar")
Run Code Online (Sandbox Code Playgroud)

这就是我让我的代码工作的方式:

["foo", "bar"].iter().any(|&s| s == test_string);
Run Code Online (Sandbox Code Playgroud)

  • `["foo", "bar"].contains(&amp;test_string)` 也完全没问题。 (7认同)