Skip to content

Instantly share code, notes, and snippets.

@eddyb
Forked from bvssvni/gist:8631956
Created January 26, 2014 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddyb/8631991 to your computer and use it in GitHub Desktop.
Save eddyb/8631991 to your computer and use it in GitHub Desktop.
/*
Tests the Any trait.
*/
pub struct Player {
name: ~str
}
pub struct Enemy {
name: ~str
}
pub trait Entity {
fn get_name<'a>(&'a self) -> &'a str;
}
impl Entity for Player {
fn get_name<'a>(&'a self) -> &'a str {
self.name.as_slice()
}
}
impl Entity for Enemy {
fn get_name<'a>(&'a self) -> &'a str {
self.name.as_slice()
}
}
fn create_player(name: ~str) -> ~Entity {
~Player { name: name } as ~Entity
}
fn main() {
// The following works:
// let player = ~Player { name: ~"player1" } as ~Any;
// The following does not work:
// Player is ~Entity.
let player = create_player(~"player1") as ~Any;
// How to make 'is' work?
let x = player;
if x.is::<Player>() {
let y = x.as_ref::<Player>().unwrap();
println!("{}", y.get_name());
}
}
// COMPILER ERROR
error: can only cast an ~-pointer to a ~-object, not a trait Entity
any.rs:42 let player = create_player(~"player1") as ~Any;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment