Zhiyao
Zhiyao

Reputation: 4414

How to match String against String in Rust?

I would like to decide whether a String begins with another String in Rust.

I saw similar questions of asking matching String against literal string in Rust, but that does not work here. 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?

Upvotes: 2

Views: 821

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70387

starts_with takes an argument which implements Pattern. There is not a Pattern instance for String, but there is one for &String.

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

Upvotes: 7

Related Questions