3 use std::collections::HashMap;
4 use std::io::{prelude::*, ErrorKind};
5 use std::fs::{self, File};
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)
113 match fs::read_to_string("Cargo.toml") {
114 Ok(s) => println!("Cargo.toml contents:\n{}\n-------------", s),
115 Err(e) => println!("Could not open Cargo.toml: {:?}", e)
119 // needs Copy trait, good for simple types
120 fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
121 let mut result = list[0];
130 // expensive for large strings, don't use that
131 fn largest_clone<T: PartialOrd + Clone>(list: &[T]) -> T {
132 let mut result = list[0].clone();
141 // good for everything, but more expensive for simple types
142 fn largest_ref<T: PartialOrd>(list: &[T]) -> &T {
143 let mut result = &list[0];
152 fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
153 if x.len() > y.len() {
161 let num_list = vec![3, 42, -7, 100, 0];
162 println!("largest number: {}", largest(&num_list));
163 println!("num_list: {:?}", num_list);
165 let char_list = vec!['a', 'y', 'q', 'm'];
166 println!("largest char: {}", largest(&char_list));
168 let str_list = vec!["hello", "world", "blue", "planet"];
169 println!("largest str: {}", largest(&str_list));
170 println!("str_list: {:?}", str_list);
172 let string_list = vec!["aaaa".to_string(), "xxxxx".to_string(), "ffff".to_string()];
173 println!("largest string (with cloning): {}", largest_clone(&string_list));
174 println!("largest string (with ref): {}", largest_ref(&string_list));
175 println!("string_list: {:?}", string_list);
177 let s1 = String::from("abcd");
181 l = longest(&s1, s2);
183 println!("longest string: {}", l);