Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: New to rust, create Python dictionary
What I like about the Python dictionary is that keys can be any atomic type. I see that I can easily convert a JSON dictionary to Rust using serde_json, but JSON requires that dictionary keys are strings. So I have created a submodule atom::Atom which uses an Enum to encapsulate atomic types, and this works. I can create a HashMap<Atom, Box<dyn Any + 'static> that works for simple types.
The problem I have run into is using a second HashMap<String, String> as a value in my Atomic HashMap. It inserts just fine, but I can't figure out how to downcast_ref() what I inserted.
Code snippet:
println!("Insert a HashMap into the HashMap.");
let mut y = HashMap::new();
y.insert("1", String::from("This is a test."));
println!("y is {:?}", y);
x.insert(Atom::BOO(true), Box::new(y));
let Some(t) = x.get(&Atom::BOO(true)) else {
panic!("Unable to access value at Atom::BOO(true).");
};
println!("Inserted {:?}", t);
let Some(t1) = t.downcast_ref::<HashMap<String, String>>() else { panic!("Ouch!"); };
println!("Inserted {:?}", t1);
Output:
Insert a HashMap into the HashMap.
y is {"1": "This is a test."}
Inserted Any { .. }
thread 'main' panicked at src/main.rs:50:71:
Ouch!
Is this doable?
3 posts - 2 participants
🏷️ rust_feed