-
-
Save eddyb/8631991 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
/* | |
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