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.
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.
11 // Test overloading of the `[]` operator. In particular test that it
12 // takes its argument *by reference*.
16 struct AssociationList<K,V> {
17 pairs: ~[AssociationPair<K,V>]
20 struct AssociationPair<K,V> {
25 impl<K,V> AssociationList<K,V> {
26 fn push(&mut self, key: K, value: V) {
27 self.pairs.push(AssociationPair {key: key, value: value});
31 impl<K:Eq,V:Copy> Index<K,V> for AssociationList<K,V> {
32 fn index(&self, index: &K) -> V {
33 for self.pairs.each |pair| {
34 if pair.key == *index {
35 return copy pair.value;
38 fail!("No value found for key: %?", index);
46 let mut list = AssociationList {pairs: ~[]};
47 list.push(copy foo, 22);
48 list.push(copy bar, 44);
50 assert!(list[foo] == 22)
51 assert!(list[bar] == 44)
53 assert!(list[foo] == 22)
54 assert!(list[bar] == 44)