I'm trying to implement my own naive HashMap/HashTable data structure in Rust. The first step is to create a table of type Vec<&mut Bucket>
where type Bucket = Vec<i64>
.
I'm having problems actually filling the table with data... I'm reading 1 000 000 integers from an input file and storing them into 100 000 buckets. For each number from the input, I assign a random bucket. I first check if the bucket already exists and if it does, I push the number onto the bucket. Otherwise, I create the bucket and store it in the table.
I have encountered two problems while doing this:
The first problem is that I get an error saying 'b' does not live long enough
while the creating the bucket. How do I preserve the bucket even after it's scope has ended?
The second problem is that I'm borrowing the table
both mutably and immutably but I'm not sure how to avoid this.
use std::env;
// other libs...
extern crate rand;
use rand::{thread_rng, Rng};
type Bucket = Vec<i64>;
fn main() {
let mut rng = thread_rng();
let mut nums = // read 1 million i64s, ie. vec![4253564645, 2394887235, ...]
println!("input consumed!");
let mut table: Vec<&mut Bucket> = Vec::new();
for x in nums.iter() {
let key: usize = rng.gen_range(0, 99999);
println!("{}", key);
if let Some(mut b) = table.get(key) { // <-- immutable borrow
b.push(x);
} else {
let mut b = vec![x]; // <-- `b` does not live long enough
table.insert(key, &mut b); // <-- mutable borrow
}
}
}
If you want to run the example the whole thing is here: https://gist.github.com/neektza/f96d8bf92ee66f1c1703
P.S. I'm using Rust 1.0.0