-
Notifications
You must be signed in to change notification settings - Fork 0
/
22_collections.rs
118 lines (85 loc) · 2.6 KB
/
22_collections.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#[derive(Debug)]
enum SpreadSheet {
Integer(i32),
Float(f64),
Text(String),
}
use std::collections::HashMap;
fn main() {
// Vectors
let mut v = Vec::new();
v.push(20);
v.push(30);
v.push(40);
println!("{:?}", v);
for i in &mut v {
println!("{}", i);
*i*=2;
println!("{}", i);
}
let v:Vec<i32> = vec![1,2,3];
println!("{:?}", v);
let value = &v[0]; // will thow an error if the value does not exist
println!("{:?}", value);
let value = &v.get(0); // Will return None if value does not exist, Some if exist
println!("{:?}", value);
// Multiple types in a vector
let row = vec![
SpreadSheet::Integer(3),
SpreadSheet::Float(3.14),
SpreadSheet::Text(String::from("Hello"))
];
println!("{:?}", row);
// String collection
// .to_string(), .push_str, .push()
let a = 1;
let mut s = a.to_string();
s.push_str(" Hello");
s.push('O');
println!("{}", s);
// + operator
let s1 = String::from("Hello");
let s2 = String::from("World");
let s3 = s1 + &s2;
println!("{}", s3);
// format! macro
let s1 = String::from("Hello");
let s2 = String::from("World");
let s3 = format!("{} {}", s1, s2);
println!("{}", s3);
// chars method
for n in "Hello".chars() {
println!("{}", n)
}
// HashMap
let mut score = HashMap::new();
score.insert("Blue", 10);
score.insert("Red", 20);
println!("{:?}", score);
// collect
let team = vec!["Blue", "Red"];
let score = vec![10, 20];
let scores:HashMap<_,_> = team.iter().zip(score.iter()).collect();
println!("{:?}", scores);
// get
let mut scores = HashMap::new();
scores.insert("Blue", 10);
scores.insert("Yellow", 20);
let score = scores.get("Yellow");
println!("{:?}", score);
// Iterate
let mut scores = HashMap::new();
scores.insert("Blue", 10);
scores.insert("Yellow", 20);
for (key, value) in &scores {
println!("{} {}", key, value);
}
// Updating HashMap
let mut score = HashMap::new();
score.insert("Blue", 10);
score.insert("Green", 15);
score.entry("Blue").or_insert(20);
score.entry("Red").or_insert(20);
score.insert("Green", 25);
println!("{:?}", score);
}