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
|
#[derive(Debug)]
struct Container<K: Eq, V> {
values: Vec<(K, V)>,
}
impl<K: Eq, V> Container<K, V> {
fn new() -> Self {
Self { values: vec![] }
}
fn insert(&mut self, k: K, v: V) {
for (actual_k, actual_v) in self.values.iter_mut() {
if actual_k == &k {
*actual_v = v;
return;
}
}
self.values.push((k, v));
}
fn get(&self, k: &K) -> Option<&V> {
for (actual_k, v) in self.values.iter().rev() {
if actual_k == k {
return Some(v);
}
}
None
}
}
fn main() {
let alice = "alice".to_string();
let bob = "bob".to_string();
let robert = "Robert".to_string();
let mut cont = Container::new();
cont.insert(bob.clone(), bob.clone());
cont.insert(bob.clone(), robert);
println!("values: {:?}", cont);
println!("{} -> {:?}", &alice, cont.get(&alice));
println!("{} -> {:?}", &bob, cont.get(&bob));
// Output should be Robert
}
|