]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/overloaded-index-assoc-list.rs
Auto merge of #28816 - petrochenkov:unistruct, r=nrc
[rust.git] / src / test / run-pass / overloaded-index-assoc-list.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Test overloading of the `[]` operator.  In particular test that it
12 // takes its argument *by reference*.
13
14
15 #![feature(core)]
16
17 use std::ops::Index;
18
19 struct AssociationList<K,V> {
20     pairs: Vec<AssociationPair<K,V>> }
21
22 #[derive(Clone)]
23 struct AssociationPair<K,V> {
24     key: K,
25     value: V
26 }
27
28 impl<K,V> AssociationList<K,V> {
29     fn push(&mut self, key: K, value: V) {
30         self.pairs.push(AssociationPair {key: key, value: value});
31     }
32 }
33
34 impl<'a, K: PartialEq + std::fmt::Debug, V:Clone> Index<&'a K> for AssociationList<K,V> {
35     type Output = V;
36
37     fn index(&self, index: &K) -> &V {
38         for pair in &self.pairs {
39             if pair.key == *index {
40                 return &pair.value
41             }
42         }
43         panic!("No value found for key: {:?}", index);
44     }
45 }
46
47 pub fn main() {
48     let foo = "foo".to_string();
49     let bar = "bar".to_string();
50
51     let mut list = AssociationList {pairs: Vec::new()};
52     list.push(foo.clone(), 22);
53     list.push(bar.clone(), 44);
54
55     assert_eq!(list[&foo], 22);
56     assert_eq!(list[&bar], 44);
57
58     assert_eq!(list[&foo], 22);
59     assert_eq!(list[&bar], 44);
60 }