string - 如何在 Rust 中匹配字符串和字符串?

标签 string rust match

我想确定一个字符串是否以 Rust 中的另一个字符串开头。

我在 Rust 中看到了类似的询问匹配字符串与文字字符串的问题,但这在这里不起作用。例如在下面的代码中,

fn main() {
    let a = String::from("hello world!");
    let b = String::from("hello");
    a.starts_with(b);
}

编译器提示:

error[E0277]: expected a `std::ops::FnMut<(char,)>` closure, found `std::string::String`
 --> temp.rs:4:7
  |
4 |     a.starts_with(b);
  |       ^^^^^^^^^^^ expected an `FnMut<(char,)>` closure, found `std::string::String`
  |
  = help: the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
  = note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `std::string::String`

我可以手动实现简单的功能,但那是重新实现轮子。我怎样才能在 Rust 中优雅地完成这项工作?

最佳答案

starts_with采用实现 Pattern 的参数. String 没有Pattern 实例,但是&String 有一个实例。

fn main() {
  let a = String::from("hello world!");
  let b = String::from("hello");
  a.starts_with(&b);
}

关于string - 如何在 Rust 中匹配字符串和字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57101650/

相关文章:

Java 正则表达式字符串#replaceAll 替代

rust - 推断调用包的名称以在过程宏中填充一个 doctest

Rust future -- 将两个 future 结合在一起

r - 生成字符变量作为ID变量

c++ - 字符串 C++ 操作

python - 在元组列表列表中查找重复项 Python

MySQL 查询过滤包含搜索字符串中任何单词的记录

c# - 正则表达式匹配任何内容,包括换行符

java - 写 !string.isEmpty() 有什么缺点吗?

rust |哪个是更好的做法 : using curly braces vs using parentheses around expression?