I am trying to implement a container which holds a list of GUI widgets where each widget needs access to that container. Each widget may need to modify other widgets on some event. For example, when a user clicks button the editor text will get updated.
I could use a boxed HashMap
but it doesn't solve the problem. What would be the easiest way to achieve what I need?
Here is what I currently have, it doesn't compile but you will get the idea:
use std::collections::HashMap;
struct SharedItem<'a> {
pub value: String,
pub store: &'a HashMap<String, SharedItem<'a>>,
}
fn trigger_button(button: &SharedItem) {
// use case where SharedItem has to be mutable
let mut editor = button.store.get(&"editor".to_string()).unwrap();
editor.value = "value inserted by button".to_string();
}
fn main() {
// map shared items by their name
let mut shared_store: HashMap<String, SharedItem> = HashMap::new();
// create components
let editor = SharedItem {
value: "editable content".to_string(),
store: &shared_store,
};
let button = SharedItem {
value: "button".to_string(),
store: &shared_store,
};
shared_store.insert("button".to_string(), button);
shared_store.insert("editor".to_string(), editor);
// now update the editor by triggering button
trigger_button(shared_store.get(&"button".to_string()).unwrap());
}