-
-
Save rust-play/c69eeb85c74603a9468232a41c1813f1 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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