Rust Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. In the folder src/bin, create a file called vecdeque.rs.
  2. Add the following code, and run it with cargo run --bin vecdeque:
1   use std::collections::VecDeque;
2
3 fn main() {
4 // A VecDeque is best thought of as a
5 // First-In-First-Out (FIFO) queue
6
7 // Usually, you will use it to push_back data
8 // and then remove it again with pop_front
9 let mut orders = VecDeque::new();
10 println!("A guest ordered oysters!");
11 orders.push_back("oysters");
12
13 println!("A guest ordered fish and chips!");
14 orders.push_back("fish and chips");
15
16 let prepared = orders.pop_front();
17 if let Some(prepared) = prepared {
18 println!("{} are ready", prepared);
19 }
20
21 println!("A guest ordered mozarella sticks!");
22 orders.push_back("mozarella sticks");
23
24 let prepared = orders.pop_front();
25 if let Some(prepared) = prepared {
26 println!("{} are ready", prepared);
27 }
28
29 println!("A guest ordered onion rings!");
30 orders.push_back("onion rings");
31
32 let prepared = orders.pop_front();
33 if let Some(prepared) = prepared {
34 println!("{} are ready", prepared);
35 }
36
37 let prepared = orders.pop_front();
38 if let Some(prepared) = prepared {
39 println!("{} are ready", prepared);
40 }
41
42 // You can freely switch your pushing
43 // from front to back and vice versa
44 let mut sentence = VecDeque::new();
45 sentence.push_back("a");
46 sentence.push_front("had");
47 sentence.push_back("little");
48 sentence.push_front("Mary");
49 sentence.push_back("Lamb");
50 println!("sentence: {:?}", sentence);
51
52 // The same applies to popping data
53 sentence.pop_front();
54 sentence.push_front("Jimmy");
55 sentence.pop_back();
56 sentence.push_back("Cat");
57 println!("sentence: {:?}", sentence);
58
59
60 // The rest of the VecDeque's methods are
61 // pretty much the same as the vector's
62 // However, the VecDeque has additional options
63 // when swap removing!
64 let mut some_queue = VecDeque::with_capacity(5);
65 some_queue.push_back("A");
66 some_queue.push_back("B");
67 some_queue.push_back("C");
68 some_queue.push_back("D");
69 some_queue.push_back("E");
70 println!("some_queue: {:?}", some_queue);
71
72 // This is the same as Vec's swap_remove
73 some_queue.swap_remove_back(2);
74 println!("some_quere after swap_remove_back: {:?}",
some_queue);
75
76 // This is the nearly the same, but swaps the removed
77 // element with the first one instead of the last one
78 some_queue.swap_remove_front(2);
79 println!("some_quere after swap_remove_front: {:?}",
some_queue);
80 }