Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created August 28, 2021 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/4064c83521bdcb7bc7764b1a3e3398f1 to your computer and use it in GitHub Desktop.
Save rust-play/4064c83521bdcb7bc7764b1a3e3398f1 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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