Crate dict [] [src]

Crate implementing real associative arrays, also known as dictionaries.

Associative arrays behave just like indexed arrays, but use unique strings as indexes instead of integers.

This associative array implementation is built as a Trait implementation over std::vec::Vec, so all Vec methods are also available for a Dict object.

Insert time is O(n²), and retrieval time is O(log n) based on key hashing. This means that it is far more efficient to query values than to insert them. If we need frequent inserts in big sets, it can be more efficient to implement a solution based on linked lists or binary heaps.

This crate is created as an exercise in extending Vec. It is more efficient to use std::collections::HashMap


use dict::{ Dict, DictIface };

//create a dictionary of strings
let mut dict = Dict::<String>::new();
assert_eq!( dict.is_empty(), true );
assert_eq!( dict.len(), 0 );

// add an element "val" indexed by the key "key"
assert_eq!( dict.add( "key".to_string(), "val".to_string() ), true );
assert_eq!( dict.is_empty(), false );
assert_eq!( dict.len(), 1 );

// keys must be unique
assert_eq!( dict.add( "key".to_string()      , "other_val".to_string() ), false );
assert_eq!( dict.len(), 1 );
assert_eq!( dict.add( "other_key".to_string(), "other_val".to_string() ), true );
assert_eq!( dict.len(), 2 );

// we can iterate just like an array
 for o in &dict {
     println!( "{} - {}", o.key, o.val );
 dict.iter().for_each( |o| println!( "{} - {}", o.key, o.val ) );

// we can access the value by its key string with get()
assert_eq!( dict.get( "key" ).unwrap(), "val" );
assert_eq!( dict.contains_key( "key" ), true );
assert_eq!( dict.remove_key( "key" ).unwrap(), "val" );
assert_eq!( dict.contains_key( "key" ), false );
assert_eq!( dict.len(), 1 );

More information

Copyleft 2018 by Ignacio Nunez Hernanz - nacho at ownyourbits dot com

GPL licensed

More at OwnYouBits





Type Definitions