-
-
Save berkus/9cff474a1ce1285c5c714e7f502908d8 to your computer and use it in GitHub Desktop.
Returning Box<dyn Self> via helper trait
This file contains hidden or 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
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