Skip to content

Instantly share code, notes, and snippets.

@miraclx
Forked from rust-play/playground.rs
Last active October 10, 2022 05:10
Show Gist options
  • Select an option

  • Save miraclx/e63036b9e510a6be6cce9a15d33f78b5 to your computer and use it in GitHub Desktop.

Select an option

Save miraclx/e63036b9e510a6be6cce9a15d33f78b5 to your computer and use it in GitHub Desktop.
Human List
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