]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/overload-index-operator.rs
auto merge of #7923 : alexcrichton/rust/add-tests, r=graydon
[rust.git] / src / test / run-pass / overload-index-operator.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 use std::ops::Index;
15
16 struct AssociationList<K,V> {
17     pairs: ~[AssociationPair<K,V>]
18 }
19
20 #[deriving(Clone)]
21 struct AssociationPair<K,V> {
22     key: K,
23     value: V
24 }
25
26 impl<K,V> AssociationList<K,V> {
27     fn push(&mut self, key: K, value: V) {
28         self.pairs.push(AssociationPair {key: key, value: value});
29     }
30 }
31
32 impl<K:Eq,V:Clone> Index<K,V> for AssociationList<K,V> {
33     fn index(&self, index: &K) -> V {
34         for self.pairs.iter().advance |pair| {
35             if pair.key == *index {
36                 return pair.value.clone();
37             }
38         }
39         fail!("No value found for key: %?", index);
40     }
41 }
42
43 pub fn main() {
44     let foo = ~"foo";
45     let bar = ~"bar";
46
47     let mut list = AssociationList {pairs: ~[]};
48     list.push(foo.clone(), 22);
49     list.push(bar.clone(), 44);
50
51     assert!(list[foo] == 22)
52     assert!(list[bar] == 44)
53
54     assert!(list[foo] == 22)
55     assert!(list[bar] == 44)
56 }