Created
November 19, 2021 11:04
-
-
Save nikomatsakis/798a08ca8099c19bcd20ac146c39d093 to your computer and use it in GitHub Desktop.
Upcast pattern
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
trait Upcast<DynTy: ?Sized> { | |
fn up(&self) -> &DynTy; | |
} | |
trait UpcastA { | |
fn up_a<'me>(&self) -> &(dyn A + 'me) | |
where | |
Self: 'me; | |
} | |
trait A: UpcastA { | |
fn a_method(&self) { | |
eprintln!("a_method"); | |
} | |
} | |
impl<T: A> UpcastA for T { | |
fn up_a<'me>(&self) -> &(dyn A + 'me) | |
where | |
Self: 'me, | |
{ | |
self | |
} | |
} | |
impl<'me, T: ?Sized + UpcastA + 'me> Upcast<dyn A + 'me> for T { | |
fn up(&self) -> &(dyn A + 'me) { | |
self.up_a() | |
} | |
} | |
trait B: A { } | |
fn foo(x: &dyn B) { | |
bar(x.up()) | |
} | |
fn bar(x: &dyn A) { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment