Skip to content

Instantly share code, notes, and snippets.

@berkus
Forked from rust-play/playground.rs
Last active March 29, 2019 16:12
Show Gist options
  • Save berkus/9cff474a1ce1285c5c714e7f502908d8 to your computer and use it in GitHub Desktop.
Save berkus/9cff474a1ce1285c5c714e7f502908d8 to your computer and use it in GitHub Desktop.
Returning Box<dyn Self> via helper trait
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