Is it possible to insert a struct into a map where the key is owned by the value being inserted?
When using hash-maps in C, this is something which I'm used to doing.
Pseudocode example:
struct MyStruct {
pub map: BTreeMap<&String, StructThatContainsString>,
// XXX ^ Rust wants lifetime specified here!
}
struct StructThatContainsString {
id: String,
other_data: u32,
}
fn my_fn() {
let ms = MyStruct { map: BTreeMap::new() };
let item = StructThatContainsString {
id: "Some Key".to_string(),
other_data: 0,
}
ms.insert(&item.id, item);
}
How can this situation be correctly handled?
If this isn't possible, could the reverse be done, where the value holds a reference to the key which would be a String
?
An alternative could be to use a set
instead of a map
, then store the entire struct
as the key, but only use one of its values when comparing (seems like it would work, but could backfire if you wanted to compare the struct
in other contexts).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…