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.
fnlike_text<S:AsRef<str>>(likes:&[S])->String{matchlikes{&[]=>"no one likes this".to_string(),&[refone]=>format!("{} likes this",one.as_ref()),&[refone,reftwo]=>format!("{} and {} like this",one.as_ref(),two.as_ref()),&[refone,reftwo,refthree]=>format!("{}, {} and {} like this",one.as_ref(),two.as_ref(),three.as_ref()),&[refone,reftwo,refrest@..]=>format!("{}, {} and {} others like this",one.as_ref(),two.as_ref(),rest.len())}}fnmain(){letlikes=["foo","bar","baz","quux"];println!("{}",like_text(&likes))}
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
ref
s 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.Permalink to the Rust Playground: play.rust-lang.org/?version=stable...