Last active
June 19, 2018 16:37
-
-
Save kooparse/211667f4a9c20ff51b5f1f0ae70cecb2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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::cell::{Ref, RefCell, RefMut}; | |
use std::collections::HashMap; | |
use std::rc::Rc; | |
pub trait MyTrait { | |
fn get_id(&self) -> i32; | |
fn print_message(&self); | |
fn mut_message(&mut self, String); | |
} | |
#[derive(Default)] | |
pub struct Object { | |
message: String, | |
id: i32, | |
} | |
impl Object { | |
pub fn new(id: i32) -> Object { | |
Object { | |
id, | |
message: String::from("\"Default message\""), | |
..Default::default() | |
} | |
} | |
} | |
impl MyTrait for Object { | |
fn get_id(&self) -> i32 { | |
self.id | |
} | |
fn print_message(&self) { | |
println!("Object {}: {}", self.id, self.message); | |
} | |
fn mut_message(&mut self, message: String) { | |
self.message = message | |
} | |
} | |
#[derive(Default)] | |
pub struct Scene { | |
objects: HashMap<i32, Rc<RefCell<MyTrait>>>, | |
} | |
impl Scene { | |
pub fn new() -> Scene { | |
Scene { | |
..Default::default() | |
} | |
} | |
pub fn add(&mut self, object: impl MyTrait + 'static) -> i32 { | |
let id = object.get_id(); | |
self.objects | |
.insert(id.clone(), Rc::new(RefCell::new(object))); | |
id | |
} | |
pub fn get(&self, id: &i32) -> Ref<MyTrait + 'static> { | |
self.objects | |
.get(id) | |
.map(|x| x.borrow()) | |
.expect("Object Not found") | |
} | |
pub fn get_mut(&mut self, id: &i32) -> RefMut<MyTrait + 'static> { | |
self.objects | |
.get_mut(id) | |
.map(|x| x.borrow_mut()) | |
.expect("Object Not found") | |
} | |
} | |
fn main() { | |
let mut scene = Scene::new(); | |
let id_0 = scene.add(Object::new(0)); | |
let id_1 = scene.add(Object::new(1)); | |
let id_2 = scene.add(Object::new(2)); | |
let s = scene.get(&id_0); | |
s.print_message(); | |
let w = scene.get(&id_1); | |
w.print_message(); | |
let z = scene.get_mut(&id_2); | |
z.print_message(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment