3
\$\begingroup\$

What's the best way to check if a String ends with any of multiple suffixes in Rust?

I have a working, naive solution:

fn string_ends_with_any(s: String, suffixes: Vec<&str>) -> bool {
 for suffix in &suffixes {
 if s.ends_with(suffix) {
 return true;
 }
 }
 false
}

Note: suffixes could have varying lengths

As I am quite new to Rust, I would very much appreciate any/all suggestions about how my code can better leverage Rust idioms.

Here are some test cases I need to function pass

#[test]
fn empty_suffixes() {
 let s = String::from("5m");
 let suffixes = vec![];
 assert!(!string_ends_with_any(s, suffixes))
}
#[test]
fn empty_string_has_no_suffix() {
 let s = String::from("");
 let suffixes = vec!["txt"];
 assert!(!string_ends_with_any(s, suffixes))
}
#[test]
fn string_ends_with_first_suffix() {
 let s = String::from("foo.txt");
 let suffixes = vec!["txt", "csv"];
 assert!(string_ends_with_any(s, suffixes))
}
#[test]
fn string_ends_with_last_suffix() {
 let s = String::from("foo.csv");
 let suffixes = vec!["txt", "csv"];
 assert!(string_ends_with_any(s, suffixes))
}
#[test]
fn string_doesnt_end_with_any_suffix() {
 let s = String::from("foo.csv");
 let suffixes = vec!["txt", "tsv"];
 assert!(!string_ends_with_any(s, suffixes))
}
#[test]
fn string_ends_in_suffix_but_case_is_wrong() {
 let s = String::from("foo.csv");
 let suffixes = vec!["txt", "Csv"];
 assert!(!string_ends_with_any(s, suffixes))
}
dfhwze
14.1k3 gold badges40 silver badges101 bronze badges
asked Sep 28, 2019 at 15:13
\$\endgroup\$
2
  • \$\begingroup\$ doc.rust-lang.org/std/string/… \$\endgroup\$ Commented Sep 28, 2019 at 16:14
  • 2
    \$\begingroup\$ @πάνταῥεῖ that's not particularly helpful. I know that String::ends_with exists (I use it in my implementation). The question I quite clearly asked was whether there is a way to test whether a String ends in any number of given strings more effectively than I am. \$\endgroup\$ Commented Sep 28, 2019 at 16:43

1 Answer 1

3
\$\begingroup\$

You could use Iterator:any to write this in a succinct way:

fn string_ends_with_any(s: String, suffixes: Vec<&str>) -> bool {
 return suffixes.iter().any(|&suffix| s.ends_with(suffix));
}

Because this pattern returns true on first match of the predicate:

for suffix in &suffixes {
 if s.ends_with(suffix) {
 return true;
 }
}
false

Whether this is rustacious remains to be seen. I'm by no means an expert in Rust.

answered Sep 28, 2019 at 17:50
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.