3 use std::collections::HashMap;
4 use std::io::{prelude::*, ErrorKind};
7 use word_utils::{first_word, second_word};
10 let s = String::from("Hello world");
11 println!("first word: '{}'", first_word(&s));
12 println!("second word: '{}'", second_word(&s).unwrap());
14 let s2 = "hello dude blah";
15 println!("second word of single: '{}'", second_word(s2).unwrap_or("(none)"));
17 match second_word(s2) {
18 Some(w) => println!("match: second word of '{}' exists: {}", s2, w),
19 None => println!("match: second word of '{}' does not exist", s2),
24 let v1 = vec![1, 2, 3];
25 println!("statically initialized vector: {:?}", v1);
27 let mut v2: Vec<String> = Vec::new();
28 v2.push("Hello".to_string());
29 v2.push(String::from("world"));
30 println!("dynamically built vector: {:?}", v2);
31 println!("first element: {}", v2[0]);
41 let mut scores = HashMap::new();
42 scores.insert("john", 10);
43 scores.insert("mary", 20);
45 println!("scores: {:?}", scores);
47 // hash map with .collect()
48 let persons = vec![("homer", 42), ("marge", 30)];
49 let collect_scores: HashMap<_, _> = persons.into_iter().collect();
50 println!("collect_scores: {:?}", collect_scores);
52 for (p, s) in &collect_scores {
53 println!("person {}: score {}", p, s);
56 println!("john's score: {}", scores.get("john").unwrap());
57 println!("jake's score: {}", scores.get("jake").unwrap_or(&-1));
60 for (_, v) in scores.iter_mut() {
63 println!("scores after doubling: {:?}", scores);
65 // double scores of immutable hashmap (rebuild it)
66 let collect_scores: HashMap<_, _> = collect_scores.iter()
67 .map(|(k, v)| (k, 2 * v))
69 println!("collect_scores after rebuilding with doubling: {:?}", collect_scores);
72 fn read_file(path: &str) -> Result<String, std::io::Error> {
73 let mut s = String::new();
75 .read_to_string(&mut s)?;
80 if let Ok(mut f) = File::open("Cargo.toml") {
81 let mut contents = String::new();
82 match f.read_to_string(&mut contents) {
83 Ok(len) => println!("successfully opened Cargo.toml: {:?}, contents {} bytes:\n{}\n----------", f, len, contents),
84 Err(e) => panic!("could not read file: {:?}", e)
87 println!("could not open Cargo.toml");
90 // alternative form, more specific error checking
91 let mut f = File::open("Cargo.toml").unwrap_or_else(|e| {
92 if e.kind() == ErrorKind::NotFound {
93 println!("Cargo.toml not found, falling back to /dev/null");
94 // need to return a File
95 File::open("/dev/null").unwrap()
97 panic!("Could not open Cargo.toml: {:?}", e);
100 let mut contents = String::new();
101 let len = f.read_to_string(&mut contents).unwrap_or_else(|e| {
102 panic!("Could not read file: {:?}", e);
104 println!("successfully opened Cargo.toml with unwrap_or_else: {:?}, contents {} bytes:\n{}\n----------", f, len, contents);
106 // using the '?' operator
107 match read_file("Cargo.toml") {
108 Ok(s) => println!("Cargo.toml contents:\n{}\n-------------", s),
109 Err(e) => println!("Could not open Cargo.toml: {:?}", e)