I'm new to Rust and am working through the exercises found on the bottom of this page. The function below converts a string into pig latin. The requirements are as follows.
Convert strings to Pig Latin, where the first consonant of each word is moved to the end of the word with an added “ay”, so “first” becomes “irst-fay”. Words that start with a vowel get “hay” added to the end instead (“apple” becomes “apple-hay”).
I would like to ensure that my code is as idiomatic as possible, specifically in the string manipulation area. Behold.
fn pigify(text: &str) -> String {
let map_func = |word: &str| -> String {
let mut chars = word.chars();
let first_char = chars.next().unwrap();
match first_char {
'a' | 'e' | 'i' | 'o' | 'u' => String::from(word) + "-hay",
_ => {
let mut xform = String::new();
for ch in chars {
xform.push(ch);
}
xform.push('-');
xform.push(first_char);
xform.push_str("ay");
xform
}
}
};
let folder = |current: String, next: String| -> String {
let mut this_str = String::new();
this_str.push_str(¤t);
if !current.is_empty() {
this_str.push(' ');
}
this_str.push_str(&next);
this_str
};
text.split_whitespace()
.map(map_func)
.fold(String::new(), folder)
}