Greet people from the command line
5 files+51−00/5 viewed
| 1 | + | /target |
| 1 | + | [package] | |
| 2 | + | name = "hello" | |
| 3 | + | version = "0.1.0" | |
| 4 | + | edition = "2021" | |
| 5 | + | description = "Greets people from the command line." | |
| 6 | + | license = "MIT" |
| 1 | + | # hello | |
| 2 | + | ||
| 3 | + | Greets people from the command line. | |
| 4 | + | ||
| 5 | + | ```sh | |
| 6 | + | $ cargo run -- Ada | |
| 7 | + | Hello, Ada! | |
| 8 | + | ``` | |
| 9 | + | ||
| 10 | + | With no name it greets whoever is signed in. | |
| 11 | + | ||
| 12 | + | ## Develop | |
| 13 | + | ||
| 14 | + | ```sh | |
| 15 | + | cargo test | |
| 16 | + | ``` |
| 1 | + | //! Greetings. | |
| 2 | + | ||
| 3 | + | /// The greeting for `name`. | |
| 4 | + | pub fn greeting(name: &str) -> String { | |
| 5 | + | format!("Hello, {name}!") | |
| 6 | + | } | |
| 7 | + | ||
| 8 | + | #[cfg(test)] | |
| 9 | + | mod tests { | |
| 10 | + | use super::*; | |
| 11 | + | ||
| 12 | + | #[test] | |
| 13 | + | fn greets_by_name() { | |
| 14 | + | assert_eq!(greeting("Ada"), "Hello, Ada!"); | |
| 15 | + | } | |
| 16 | + | } |
| 1 | + | use std::env; | |
| 2 | + | ||
| 3 | + | use hello::greeting; | |
| 4 | + | ||
| 5 | + | fn main() { | |
| 6 | + | // The name given, or whoever is signed in. | |
| 7 | + | let name = env::args() | |
| 8 | + | .nth(1) | |
| 9 | + | .or_else(|| env::var("USER").ok()) | |
| 10 | + | .unwrap_or_else(|| "world".to_owned()); | |
| 11 | + | println!("{}", greeting(&name)); | |
| 12 | + | } |