Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
struct Entry<K,V> {
key: K,
value: V,
}
struct AssociativeArray<K,V> {
contents: ~[Entry<K,V>]
}
impl<K:Eq,V> AssociativeArray<K,V> {
fn new() -> AssociativeArray<K,V> {
AssociativeArray {
contents: ~[]
}
}
fn index_of(&self, key: &K) -> Option<uint> {
/*!
* Returns the index in self.contents where
* the entry for `key` occurs, or `None`
* there is no such index.
*/
fail!()
}
fn insert(&mut self, key: K, value: V) {
/*!
* Adds a new entry for `key`, overwriting
* any old entry with the value `value`
*/
fail!()
}
fn find<'a>(&'a self, key: &K) -> Option<&'a V> {
/*!
* Returns the value for the key `key`, or
* `None` if there is no entry for `key`.
*/
fail!()
}
fn remove(&mut self, key: &K) {
/*!
* Removes the value for `key`, if any.
*/
fail!()
}
}
#[test]
fn index_of() {
let array = AssociativeArray { contents: ~[ Entry { key: 1, value: 2 } ] };
assert!(array.index_of(&1) == Some(0));
assert!(array.index_of(&2) == None);
}
#[test]
fn find_not_present() {
let array: AssociativeArray<int, int> =
AssociativeArray::new();
assert!(array.find(&1).is_none());
}
#[test]
fn insert_and_find() {
let mut array = AssociativeArray::new();
array.insert(22, 44);
array.insert(44, 66);
assert!(array.find(&100).is_none());
assert_eq!(*array.find(&22).unwrap(), 44);
array.insert(22, 88);
assert_eq!(*array.find(&22).unwrap(), 88);
}
#[test]
fn remove() {
let mut array = AssociativeArray::new();
array.insert(22, 44);
array.insert(44, 66);
assert_eq!(*array.find(&22).unwrap(), 44);
assert_eq!(*array.find(&44).unwrap(), 66);
array.remove(&22);
assert!(array.find(&22).is_none());
assert_eq!(*array.find(&44).unwrap(), 66);
}

Loops and conditionals

let mut i = 0;
while i < 3 {
    i += 1;
}
let mut i = 0;
loop {
    if i >= 3 { break; }
    i += 1;
}
for i in range(0, 3) {
    ...
}

Enums

let opt = Some(3);
match opt {
  Some(ref v) => { ... }
  None => { ... }
}

Vectors

let mut v = ~[];
v.push(1);     // Append an element.
v.push(2);
v.push(3);
v.swap(0, 2);  // Exchange two elements.
v.pop();       // Remove and return last element.

Borrowing and references

fn get_key<'a>(entry: &'a Entry<int, int>) -> &'a int {
  &entry.key
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment