]> git.lizzy.rs Git - rust.git/blob - tests/ui/overloaded/overloaded-index-assoc-list.rs
Rollup merge of #106717 - klensy:typo, r=lcnr
[rust.git] / tests / ui / overloaded / overloaded-index-assoc-list.rs
1 // run-pass
2 // Test overloading of the `[]` operator.  In particular test that it
3 // takes its argument *by reference*.
4
5 use std::ops::Index;
6
7 struct AssociationList<K,V> {
8     pairs: Vec<AssociationPair<K,V>> }
9
10 #[derive(Clone)]
11 struct AssociationPair<K,V> {
12     key: K,
13     value: V
14 }
15
16 impl<K,V> AssociationList<K,V> {
17     fn push(&mut self, key: K, value: V) {
18         self.pairs.push(AssociationPair {key: key, value: value});
19     }
20 }
21
22 impl<'a, K: PartialEq + std::fmt::Debug, V:Clone> Index<&'a K> for AssociationList<K,V> {
23     type Output = V;
24
25     fn index(&self, index: &K) -> &V {
26         for pair in &self.pairs {
27             if pair.key == *index {
28                 return &pair.value
29             }
30         }
31         panic!("No value found for key: {:?}", index);
32     }
33 }
34
35 pub fn main() {
36     let foo = "foo".to_string();
37     let bar = "bar".to_string();
38
39     let mut list = AssociationList {pairs: Vec::new()};
40     list.push(foo.clone(), 22);
41     list.push(bar.clone(), 44);
42
43     assert_eq!(list[&foo], 22);
44     assert_eq!(list[&bar], 44);
45
46     assert_eq!(list[&foo], 22);
47     assert_eq!(list[&bar], 44);
48 }