Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created October 7, 2022 03:27
Show Gist options
  • Select an option

  • Save rust-play/c69eeb85c74603a9468232a41c1813f1 to your computer and use it in GitHub Desktop.

Select an option

Save rust-play/c69eeb85c74603a9468232a41c1813f1 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
fn human_list<I, T>(i: I) -> String
where
I: Iterator<Item = T>,
T: AsRef<str>,
{
let mut items = i.peekable();
let mut s = match items.next() {
Some(s) => s.as_ref().to_owned(),
None => return String::new(),
};
while let Some(i) = items.next() {
s += if items.peek().is_some() {
", "
} else {
" and "
};
s += i.as_ref();
}
return s;
}
fn main() {
println!("{}", human_list(["1"].iter()));
println!("{}", human_list(["1", "2"].iter()));
println!("{}", human_list(["1", "2", "3"].iter()));
println!("{}", human_list(["1", "2", "3", "4"].iter()));
println!("{}", human_list(["1", "2", "3", "4", "5"].iter()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment