DEV Community

Discussion on: Daily Challenge #266 - Who Likes It?

Collapse
 
benaryorg profile image
#benaryorg

Strings in Rust are a bit tedious since you usually want to avoid extra allocations and there's ownership concerns, so this code has a lot more refs than I'd like, and the function signature is a classic, but otherwise I think it's kind of pretty.
What I like most is that there's no -2 for the length, because Rust pattern matching lets me capture the elements into another slice right there.

fn like_text<S: AsRef<str>>(likes: &[S]) -> String
{
    match likes
    {
        &[] => "no one likes this".to_string(),
        &[ref one] => format!("{} likes this", one.as_ref()),
        &[ref one, ref two] => format!("{} and {} like this", one.as_ref(), two.as_ref()),
        &[ref one, ref two, ref three] => format!("{}, {} and {} like this", one.as_ref(), two.as_ref(), three.as_ref()),
        &[ref one, ref two, ref rest@..] => format!("{}, {} and {} others like this", one.as_ref(), two.as_ref(), rest.len())
    }
}

fn main()
{
    let likes = ["foo", "bar", "baz", "quux"];

    println!("{}", like_text(&likes))
}

Permalink to the Rust Playground: play.rust-lang.org/?version=stable...