Hello,
it's the first time I post here, so sorry for any mistakes.
I don't know why this is not possible. The HashMap should return a reference to data inside it. Why does it need the content of variable k2?
Furthermore it is possible to drop k2 and the code is still accepted. However, if I drop k2_data than it is a problem.
Can anyone explain the lifetimes in this scenario and what exactly is the problem here?
use std::collections::HashMap;
#[derive(Hash, PartialEq, Eq, Debug)]
struct Key<'k> {
id: &'k Data
}
#[derive(Debug)]
struct Value<'v> {
id: &'v Data
}
#[derive(Hash, PartialEq, Eq, Debug)]
struct Data {
val: i32
}
struct Test<'k, 'v> {
pub data: HashMap<Key<'k>, Value<'v>>
}
fn main() {
// +++ create HashMap and insert data +++
let mut test = Test { data: HashMap::new() };
let k1_data = Data { val: 1 };
let k1 = Key { id: &k1_data };
let v1_data = Data { val: 10 };
let v1 = Value { id: &v1_data };
test.data.insert(k1, v1);
// +++ access data +++
// create key
let k2_data = Data { val: 1 };
let k2 = Key { id: &k2_data };
// get value
let v2 = test.data.get(&k2);
println!("{:?}: {:?}", k2, v2.unwrap());
//drop(k2); // no problem
drop(k2_data); // Here is the problem. Why?
println!("{:?}", v2.unwrap());
}
Thanks for any help.