Skip to content

Instantly share code, notes, and snippets.

@aboglioli
Created May 8, 2020 04:48
Show Gist options
  • Save aboglioli/1f6041bfc9917a31d61368fb761840f5 to your computer and use it in GitHub Desktop.
Save aboglioli/1f6041bfc9917a31d61368fb761840f5 to your computer and use it in GitHub Desktop.
Share struct property (owned) with childs through reference.
use core::fmt::Debug;
use std::rc::Rc;
#[derive(Debug)]
struct Display;
impl Display {
fn print<T: Debug>(&self, t: &T) {
println!("> {:?}", t);
}
}
#[derive(Debug)]
struct Window {
d: Rc<Display>,
id: u32,
}
impl Window {
fn proc(&self) {
self.d.print(self);
}
}
struct Container {
d: Rc<Display>,
windows: Vec<Window>,
}
impl Container {
fn add_window(&mut self) {
let w = Window { d: Rc::clone(&self.d), id: 32 };
self.windows.push(w);
}
fn proc(&self) {
for w in self.windows.iter() {
w.proc();
}
}
}
fn main() {
let d = Display;
let mut c = Container { windows: Vec::new(), d: Rc::new(d) };
c.add_window();
c.proc();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment