[英]How to match String against String in Rust?
I would like to decide whether a String begins with another String in Rust. 我想判断一个String是否以Rust中的另一个字符串开头。
I saw similar questions of asking matching String against literal string in Rust, but that does not work here. 我在Rust中看到了类似的问题,要求匹配String和文字字符串,但这在这里不起作用。 For example in the following code, 例如,在以下代码中,
fn main() {
let a = String::from("hello world!");
let b = String::from("hello");
a.starts_with(b);
}
The compiler complains: 编译器抱怨:
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`
I could implement the simple function manually, but that is reimplementing wheels. 我可以手动实现简单的功能,但这是重新实现轮子。 How can I get this done gracefully in Rust? 如何在Rust中优雅地完成这项工作?
starts_with
takes an argument which implements Pattern
. starts_with
接受一个实现Pattern
的参数。 There is not a Pattern
instance for String
, but there is one for &String
. String
没有Pattern
实例,但是有一个用于&String
。
fn main() {
let a = String::from("hello world!");
let b = String::from("hello");
a.starts_with(&b);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.