1

I want to build a HashMap of a vector of structures where the key is a String field in the structure and the value is the structure itself. It seems like this should be possible without copying. I want to move the lifetime of the structure to the HashMap and then the key would have the same lifetime since it's valid as long as the HashMap contains the structure.

use std::collections::{HashMap};

#[derive(Hash, PartialEq, Eq)]
struct A {
    pub x: String,
}

fn main() {
    let mut map = HashMap::new();
    let mut vec = Vec::new();
    vec.push(A { x: "foo".to_string() });
    for x in vec {
        map.insert(&x.x, x);
    }
}

This gives me the following error

src/main.rs:13:19: 13:22 error: `x.x` does not live long enough
src/main.rs:13       map.insert(&x.x, x);
                                 ^~~
src/main.rs:9:34: 15:2 note: reference must be valid for the block suffix following statement 0 at 9:33...
src/main.rs: 9     let mut map = HashMap::new();
src/main.rs:10     let mut vec = Vec::new();
src/main.rs:11     vec.push(A { x: "foo".to_string() });
src/main.rs:12     for x in vec {
src/main.rs:13       map.insert(&x.x, x);
src/main.rs:14     }
               ...
src/main.rs:12:5: 14:6 note: ...but borrowed value is only valid for the for at 12:4
src/main.rs:12     for x in vec {
src/main.rs:13       map.insert(&x.x, x);
src/main.rs:14     }

Any help sorting this out is greatly appreciated!

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Michael Mior
  • 28,107
  • 9
  • 89
  • 113
  • 1
    You cannot do this. For one, you are trying to take a reference to a value where the address is only valid for the one statement before it's moved. You also [can't store a value and a reference to that value in the same struct](http://stackoverflow.com/q/32300132/155423), so the end goal is unreachable. Also, note that the [vector has nothing to do with your question](http://is.gd/vh6kD6). – Shepmaster Mar 19 '16 at 00:45
  • 1
    *the key would have the same lifetime since it's valid as long as the HashMap contains the structure* — not true; as soon as the `HashMap` decides to reallocate the storage of the values, any references would be invalidated. – Shepmaster Mar 19 '16 at 00:52
  • @Shepmaster Well, it is true that the key will not be dropped until the value is removed from the HashMap. That was the point I was trying to make. I see the point you're making in your earlier comment though. Thanks! – Michael Mior Mar 19 '16 at 02:21

0 Answers0