[英]How to match String against String in Rust?
我想判斷一個String是否以Rust中的另一個字符串開頭。
我在Rust中看到了類似的問題,要求匹配String和文字字符串,但這在這里不起作用。 例如,在以下代碼中,
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.