如何在Rust中将String与String进行匹配?

Zhi*_* Ma 2 string match rust

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

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

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

编译器抱怨:

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

我可以手动实现简单的功能,但这就是重新实现轮子。如何在Rust中很好地完成此工作?

Sil*_*olo 7

starts_with接受一个实现的参数Pattern。没有一个Pattern实例String,但是有一个实例&String

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