0

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

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
neektza
  • 483
  • 6
  • 11
  • Please make your example code a [MCVE](/help/mcve). For example, you don't need to include *any* randomness to reproduce your error. Additionally, you can just provide a *single* value to `nums`. Make your code small, make it reproduce one problem, and ideally make it run on the [Playpen](https://play.rust-lang.org/). Please have the curtesy to spend a bit of time when asking in order to save the time of many people who will read this to learn or attempt to answer. – Shepmaster Jun 07 '15 at 20:26
  • You are asking two questions (another thing to please not do). I've marked this as a duplicate of one of them. For your other question, please review [the multitude of questions about that error](http://stackoverflow.com/search?q=%5Brust%5D+does+not+live+long+enough) and potentially ask a new question, detailing (a) why your problem is different or (b) what you don't understand about them. – Shepmaster Jun 07 '15 at 20:28

0 Answers0