Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created March 29, 2019 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rust-play/c6d6fd68eb2d8d6e4a6e0ba7764bb81d to your computer and use it in GitHub Desktop.
Save rust-play/c6d6fd68eb2d8d6e4a6e0ba7764bb81d to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
trait Trait: AsTrait {
fn get_answer(&self) -> i32;
}
struct S;
impl Trait for S {
fn get_answer(&self) -> i32 { 42 }
}
trait AsTrait {
fn as_trait(&self) -> &Trait;
}
impl<T> AsTrait for T where T: Trait {
fn as_trait(&self) -> &Trait {
self
}
}
fn main() {
let s = Box::new(S) as Box<dyn Trait>;
let t = s.as_trait();
println!("{}", t.get_answer());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment