我想确定一个字符串是否以 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/