This is my implementation of the Pig Latin recommended exercise in The Rust Programming Language book. I am using the unicode segmentation crate to split the string into words while also keeping the delimiters. Any pointers on making this code more idiomatic or run more optimal?
use unicode_segmentation::UnicodeSegmentation;
#[allow(overlapping_patterns)]
fn translate_word(s: &str) -> String {
let mut it = s.chars();
let first = it.next().unwrap();
match first.to_ascii_lowercase() {
'a' | 'e' | 'i' | 'o' | 'u' => format!("{}-hay", s),
'a'..='z' => format!("{}-{}ay", it.collect::<String>(), first),
_ => s.to_string(),
}
}
pub fn translate(s: &str) -> String {
s.split_word_bounds()
.map(translate_word)
.collect::<Vec<_>>()
.join("")
}
The code is inside a module named pig_latin
.