Skip to content

Instantly share code, notes, and snippets.

@nikomatsakis
Created November 19, 2021 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikomatsakis/798a08ca8099c19bcd20ac146c39d093 to your computer and use it in GitHub Desktop.
Save nikomatsakis/798a08ca8099c19bcd20ac146c39d093 to your computer and use it in GitHub Desktop.
Upcast pattern
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