4 use std::collections::HashMap;
5 use std::fs::{self, File};
6 use std::io::{prelude::*, ErrorKind};
7 use std::{sync, thread, time};
10 use word_utils::{first_word, second_word};
13 let s = String::from("Hello world");
14 println!("first word: '{}'", first_word(&s));
15 println!("second word: '{}'", second_word(&s).unwrap());
17 let s2 = "hello dude blah";
19 "second word of single: '{}'",
20 second_word(s2).unwrap_or("(none)")
23 match second_word(s2) {
24 Some(w) => println!("match: second word of '{}' exists: {}", s2, w),
25 None => println!("match: second word of '{}' does not exist", s2),
30 let v1 = vec![1, 2, 3];
31 println!("statically initialized vector: {:?}", v1);
33 let mut v2: Vec<String> = Vec::new();
34 v2.push("Hello".to_string());
35 v2.push(String::from("world"));
36 println!("dynamically built vector: {:?}", v2);
37 println!("first element: {}", v2[0]);
47 let mut scores = HashMap::new();
48 scores.insert("john", 10);
49 scores.insert("mary", 20);
51 println!("scores: {:?}", scores);
53 // hash map with .collect()
54 let persons = vec![("homer", 42), ("marge", 30)];
55 let collect_scores: HashMap<_, _> = persons.into_iter().collect();
56 println!("collect_scores: {:?}", collect_scores);
58 for (p, s) in &collect_scores {
59 println!("person {}: score {}", p, s);
62 println!("john's score: {}", scores.get("john").unwrap());
63 println!("jake's score: {}", scores.get("jake").unwrap_or(&-1));
66 for (_, v) in scores.iter_mut() {
69 println!("scores after doubling: {:?}", scores);
71 // double scores of immutable hashmap (rebuild it)
72 let collect_scores: HashMap<_, _> = collect_scores
74 .map(|(k, v)| (k, 2 * v))
77 "collect_scores after rebuilding with doubling: {:?}",
83 if let Ok(mut f) = File::open("Cargo.toml") {
84 let mut contents = String::new();
85 match f.read_to_string(&mut contents) {
87 "successfully opened Cargo.toml: {:?}, contents {} bytes:\n{}\n----------",
90 Err(e) => panic!("could not read file: {:?}", e),
93 println!("could not open Cargo.toml");
96 // alternative form, more specific error checking
97 let mut f = File::open("Cargo.toml").unwrap_or_else(|e| {
98 if e.kind() == ErrorKind::NotFound {
99 println!("Cargo.toml not found, falling back to /dev/null");
100 // need to return a File
101 File::open("/dev/null").unwrap()
103 panic!("Could not open Cargo.toml: {:?}", e);
106 let mut contents = String::new();
107 let len = f.read_to_string(&mut contents).unwrap_or_else(|e| {
108 panic!("Could not read file: {:?}", e);
110 println!("successfully opened Cargo.toml with unwrap_or_else: {:?}, contents {} bytes:\n{}\n----------", f, len, contents);
112 // using the '?' operator
113 match read_file("Cargo.toml") {
114 Ok(s) => println!("Cargo.toml contents:\n{}\n-------------", s),
115 Err(e) => println!("Could not open Cargo.toml: {:?}", e),
119 match fs::read_to_string("Cargo.toml") {
120 Ok(s) => println!("Cargo.toml contents:\n{}\n-------------", s),
121 Err(e) => println!("Could not open Cargo.toml: {:?}", e),
126 let num_list = vec![3, 42, -7, 100, 0];
127 println!("largest number: {}", largest(&num_list));
128 println!("num_list: {:?}", num_list);
130 let char_list = vec!['a', 'y', 'q', 'm'];
131 println!("largest char: {}", largest(&char_list));
133 let str_list = vec!["hello", "world", "blue", "planet"];
134 println!("largest str: {}", largest(&str_list));
135 println!("str_list: {:?}", str_list);
137 let string_list = vec!["aaaa".to_string(), "xxxxx".to_string(), "ffff".to_string()];
139 "largest string (with cloning): {}",
140 largest_clone(&string_list)
142 println!("largest string (with ref): {}", largest_ref(&string_list));
143 println!("string_list: {:?}", string_list);
145 let s1 = String::from("abcd");
149 l = longest(&s1, s2);
151 println!("longest string: {}", l);
155 let mut expensive_int_result = Cacher::new(|x| {
156 println!("calculating expensive int result for {}", x);
161 "1st int call for value 1: {}",
162 expensive_int_result.value(1)
165 "2nd int call for value 1: {}",
166 expensive_int_result.value(1)
169 "1st int call for value 2: {}",
170 expensive_int_result.value(2)
173 let mut expensive_str_result = Cacher::new(|x: &str| {
174 println!("calculating expensive str result for {}", x);
179 "1st int call for value abc: {}",
180 expensive_str_result.value("abc")
183 "2nd int call for value abc: {}",
184 expensive_str_result.value("abc")
187 "1st int call for value defg: {}",
188 expensive_str_result.value("defg")
192 fn test_iterators() {
193 let v1 = vec!["Hello", "good", "world"];
194 // implied default is .into_iter() which consumes v1
196 println!("element: {}", s);
198 // can still use it now
199 println!("v1: {:?}", &v1);
202 let mut v1_iter = v1.iter();
203 while let Some(e) = v1_iter.next() {
204 println!("while loop over iter: {}", e);
207 for l_element in v1.iter().filter(|x| x.contains('l')) {
208 println!("v1 element containing 'l': {}", l_element);
211 let v2 = vec![1, 2, 3];
212 let double_v2: Vec<_> = v2.iter().map(|x| x * 2).collect();
213 println!("doubled v2: {:?}", double_v2);
215 for i in v2.into_iter().map(|x| x * 3) {
216 println!("for loop triplicating v2: {}", i);
219 for i in Counter5::new() {
220 println!("Counter 5 value: {}", i);
225 let t1 = thread::spawn(|| {
227 println!("hello #{} from thread", i);
228 thread::sleep(time::Duration::from_millis(1));
233 println!("hello #{} from main", i);
234 thread::sleep(time::Duration::from_millis(1));
240 let (tx1, rx) = sync::mpsc::channel();
241 let tx2 = tx1.clone();
243 let sender1 = thread::spawn(move || {
244 for s in ["hey", "from", "sender", "one"] {
245 tx1.send(s).expect("failed to send");
246 thread::sleep(time::Duration::from_millis(100));
250 let sender2 = thread::spawn(move || {
251 for s in ["Servus", "von", "Produzent", "zwei"] {
252 tx2.send(s).expect("failed to send");
253 thread::sleep(time::Duration::from_millis(100));
258 println!("received {} from mpsc", received);
261 sender1.join().unwrap();
262 sender2.join().unwrap();
265 let counter = sync::Arc::new(sync::Mutex::new(0));
266 let mut threads = vec![];
268 let tc = sync::Arc::clone(&counter);
269 threads.push(thread::spawn(move || {
270 *tc.lock().unwrap() += 1;
278 println!("counter: {}", *counter.lock().unwrap());
281 fn test_dyn_traits() {
282 let text = "I ate a salad for lunch today";
283 let mut post = Post::new();
285 assert_eq!("", post.content());
287 post.request_review();
288 assert_eq!("", post.content());
291 assert_eq!("", post.content());
293 post.request_review();
294 assert_eq!("", post.content());
296 post.approve(); // first
297 assert_eq!("", post.content());
299 post.approve(); // second
300 assert_eq!(text, post.content());
302 post.reject(); // no-op
303 assert_eq!(text, post.content());
306 fn test_state_types() {
307 let mut post = TPost::new();
308 post.add_text("I ate a salad for lunch");
309 let post = post.request_review();
310 let mut post = post.reject();
311 post.add_text(" today");
312 let post = post.request_review();
313 let post = post.approve();
314 assert_eq!(post.content(), "I ate a salad for lunch today");