-
-
Save rust-play/4064c83521bdcb7bc7764b1a3e3398f1 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::HashMap; | |
trait Iface { | |
fn fun(&mut self, c: &mut Container); | |
} | |
struct Container { | |
map: HashMap<i32, Box<dyn Iface>>, | |
} | |
impl Container { | |
fn do_it(&mut self) { | |
if let Some(i) = self.map.get_mut(&123) { | |
//if let Some(mut i) = self.map.remove(&123) { | |
i.fun(self); | |
//self.map.insert(123, i); | |
} else { | |
panic!("unexpected"); | |
} | |
} | |
} | |
struct Thing {} | |
impl Iface for Thing { | |
fn fun(&mut self, c: &mut Container) { | |
c.map.insert(456, Box::new(Thing{})); | |
} | |
} | |
fn main() { | |
let mut c = Container{map:HashMap::new()}; | |
c.map.insert(123, Box::new(Thing{})); | |
c.do_it(); | |
for key in c.map.keys() { | |
println!("{}", key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment