Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust - idiomatic way to check if a string starts with one of a set of substrings

Tags:

string

rust

core::str
pub fn starts_with<'a, P>(&'a self, pat: P) -> bool
where
    P: Pattern<'a>,

Returns true if the given pattern matches a prefix of this string slice.

Returns false if it does not.

The pattern can be a &str, [char], a slice of [char]s, or a function or closure that determines if a character matches.

What's the idiomatic way to see if a string starts with one of a set of substrings?

if applesauce.starts_with(['a', 'b', 'c', 'd']) {
    // elegant if you're looking to match a single character
}

if applesauce.starts_with("aaa") || applesauce.starts_with("bbb") || applesauce.starts_with("ccc") || applesauce.starts_with("ddd") {
    // there *must* be a better way!
}
like image 794
Jack Deeth Avatar asked Sep 05 '25 00:09

Jack Deeth


1 Answers

You can use iterators:

if ["aaa", "bbb", "ccc", "ddd"].iter().any(|s| applesauce.starts_with(*s)) {
    // there *must* be a better way!
}
like image 159
Chayim Friedman Avatar answered Sep 07 '25 19:09

Chayim Friedman