2
\$\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))
}
\$\endgroup\$
  • \$\begingroup\$ doc.rust-lang.org/std/string/… \$\endgroup\$ – πάντα ῥεῖ Sep 28 '19 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\$ – Michael Hall Sep 28 '19 at 16:43
2
\$\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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.