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);
73 if let Ok(mut f) = File::open("Cargo.toml") {
74 let mut contents = String::new();
75 match f.read_to_string(&mut contents) {
76 Ok(len) => println!("successfully opened Cargo.toml: {:?}, contents {} bytes:\n{}\n----------", f, len, contents),
77 Err(e) => panic!("could not read file: {:?}", e)
80 println!("could not open Cargo.toml");
83 // alternative form, more specific error checking
84 let mut f = File::open("Cargo.toml").unwrap_or_else(|e| {
85 if e.kind() == ErrorKind::NotFound {
86 println!("Cargo.toml not found, falling back to /dev/null");
87 // need to return a File
88 File::open("/dev/null").unwrap()
90 panic!("Could not open Cargo.toml: {:?}", e);
93 let mut contents = String::new();
94 let len = f.read_to_string(&mut contents).unwrap_or_else(|e| {
95 panic!("Could not read file: {:?}", e);
97 println!("successfully opened Cargo.toml with unwrap_or_else: {:?}, contents {} bytes:\n{}\n----------", f, len, contents);