Created
January 26, 2014 22:49
-
-
Save karl-zylinski/8640508 to your computer and use it in GitHub Desktop.
This file contains 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
pub trait Entity { | |
// ... some irrelevant functions | |
} | |
impl<'a> AnyRefExt<'a> for &'a ~Entity { | |
#[inline] | |
fn is<T: 'static>(self) -> bool { | |
// Get TypeId of the type this function is instantiated with | |
let t = TypeId::of::<T>(); | |
// Get TypeId of the type in the trait object | |
let boxed = self.get_type_id(); | |
// Compare both TypeIds on equality | |
t == boxed | |
} | |
#[inline] | |
fn as_ref<T: 'static>(self) -> Option<&'a T> { | |
if self.is::<T>() { | |
Some(unsafe { transmute(self.as_void_ptr()) }) | |
} else { | |
None | |
} | |
} | |
} | |
// In my enemy implementation, I want to find the player from a ~[~Entity] vector (which contains all enemies and the player). Like this: | |
impl Entity for Enemy { | |
fn update(&self, dt: f32, world: &World, _input: &Input) -> UpdateResult { | |
let player_entity = match world.entities.iter().find(|&e| (*e).is::<~Player>()) { | |
Some(player) => player.as_ref::<~Player>(), | |
None => fail!("No player found in world.") | |
}; | |
// irrelevant code removed | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment