2013-03-26 15:04:30 -04:00
|
|
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
// except according to those terms.
|
|
|
|
|
|
|
|
// Test overloading of the `[]` operator. In particular test that it
|
|
|
|
// takes its argument *by reference*.
|
|
|
|
|
2013-05-20 17:07:24 -07:00
|
|
|
use std::ops::Index;
|
2013-03-26 15:04:30 -04:00
|
|
|
|
|
|
|
struct AssociationList<K,V> {
|
2014-03-05 14:02:44 -08:00
|
|
|
pairs: Vec<AssociationPair<K,V>> }
|
2013-03-26 15:04:30 -04:00
|
|
|
|
2013-07-02 12:47:32 -07:00
|
|
|
#[deriving(Clone)]
|
2013-03-26 15:04:30 -04:00
|
|
|
struct AssociationPair<K,V> {
|
|
|
|
key: K,
|
|
|
|
value: V
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<K,V> AssociationList<K,V> {
|
|
|
|
fn push(&mut self, key: K, value: V) {
|
|
|
|
self.pairs.push(AssociationPair {key: key, value: value});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-10-14 21:07:11 -04:00
|
|
|
impl<K: PartialEq + std::fmt::Show, V:Clone> Index<K,V> for AssociationList<K,V> {
|
2014-07-03 14:32:41 -07:00
|
|
|
fn index<'a>(&'a self, index: &K) -> &'a V {
|
2013-08-03 12:45:23 -04:00
|
|
|
for pair in self.pairs.iter() {
|
2013-03-26 15:04:30 -04:00
|
|
|
if pair.key == *index {
|
2014-07-03 14:32:41 -07:00
|
|
|
return &pair.value
|
2013-03-26 15:04:30 -04:00
|
|
|
}
|
|
|
|
}
|
2014-10-09 15:17:22 -04:00
|
|
|
panic!("No value found for key: {}", index);
|
2013-03-26 15:04:30 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn main() {
|
2014-05-25 03:10:11 -07:00
|
|
|
let foo = "foo".to_string();
|
|
|
|
let bar = "bar".to_string();
|
2013-03-26 15:04:30 -04:00
|
|
|
|
2014-03-05 14:02:44 -08:00
|
|
|
let mut list = AssociationList {pairs: Vec::new()};
|
2014-04-21 17:58:52 -04:00
|
|
|
list.push(foo.clone(), 22i);
|
|
|
|
list.push(bar.clone(), 44i);
|
2013-03-26 15:04:30 -04:00
|
|
|
|
2013-03-28 18:39:09 -07:00
|
|
|
assert!(list[foo] == 22)
|
|
|
|
assert!(list[bar] == 44)
|
2013-03-26 15:04:30 -04:00
|
|
|
|
2013-03-28 18:39:09 -07:00
|
|
|
assert!(list[foo] == 22)
|
|
|
|
assert!(list[bar] == 44)
|
2013-05-06 00:18:51 +02:00
|
|
|
}
|