Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::HashMap;
- struct A {}
- struct B {}
- trait MyTrait {
- fn print_hello(&self);
- }
- impl MyTrait for A {
- fn print_hello(&self) {
- println!("I am A");
- }
- }
- impl MyTrait for B {
- fn print_hello(&self) {
- println!("I am B");
- }
- }
- fn main() {
- let a = Box::new(A {});
- let b = Box::new(B {});
- let mut dict: HashMap<&str, Box<dyn MyTrait>> = HashMap::new();
- dict.insert("a", a);
- dict.insert("b", b);
- match dict.get("a") {
- Some(my_trait) => {
- my_trait.print_hello();
- }
- None => {
- println!("Struct not found");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement