Created
April 18, 2016 15:36
-
-
Save anonymous/652a4a6e60b1ce857e48e201eec67115 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
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::rc::Rc; | |
use std::ops::Deref; | |
//A HasPosition trait and a Body that implements it | |
trait HasPosition { | |
fn get_position(&self) -> i32; | |
} | |
struct Body { | |
position: i32 | |
} | |
impl HasPosition for Body { | |
fn get_position(&self) -> i32 { | |
self.position | |
} | |
} | |
//First try - accepts anything that implements HasPosition | |
struct Force<T> where T: HasPosition { | |
apply_to: T, | |
value: i32, | |
} | |
impl<T> Force<T> where T: HasPosition { | |
fn apply(&self) { | |
println!("{}", self.value + self.apply_to.get_position()); | |
} | |
} | |
//Second try - accepts anything that derefs to something | |
//that implements HasPosition | |
struct ForceB<D, T> where T: Deref<Target=D>, D: HasPosition { | |
apply_to: T, | |
value: i32, | |
} | |
impl<D, T> ForceB<D, T> where T: Deref<Target=D>, D: HasPosition { | |
fn apply(&self) { | |
println!("{}", self.value + self.apply_to.get_position()); | |
} | |
} | |
//Stupid idea? - implement HasPosition for anything | |
//that derefs to something that implements HasPosition. | |
//This should _recursively_ implement HasPosition? | |
//Does not work | |
impl<T, U> HasPosition for U where T: HasPosition, U: Deref<Target=T> { | |
fn get_position(&self) -> i32 { | |
self.deref().get_position() | |
} | |
} | |
fn main() { | |
//works | |
let body = Body { position: 50 }; | |
let force = Force { apply_to: body, value: 2 }; | |
force.apply(); | |
//works with the second struct | |
let rc_body = Rc::new(Body { position: 50 }); | |
let rc_force = ForceB { apply_to: rc_body, value: 2 }; | |
rc_force.apply(); | |
//but does not work recursively | |
let rc_rc_body = Rc::new(Rc::new(Body { position: 50 })); | |
let rc_rc_force = ForceB { apply_to: rc_rc_body, value: 2 }; | |
rc_force.apply(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment