Skip to content

Instantly share code, notes, and snippets.

@karl-zylinski
Created January 26, 2014 22:49
Show Gist options
  • Save karl-zylinski/8640508 to your computer and use it in GitHub Desktop.
Save karl-zylinski/8640508 to your computer and use it in GitHub Desktop.
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