-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Experience report: Integration with Any
#2
Comments
FWIW there is a more ergonomic approach that doesn't require upcasting, via an pub trait AsAny: Any {
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
impl<T: Any> AsAny for T {
#[inline(always)]
fn as_any(&self) -> &dyn Any {
self
}
#[inline(always)]
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
} Adding that as a supertrait gives basically the same ergonomics as trait upcasting (each node doesn't have to do anything). But of course not having to define such a trait is much nicer. :) |
Also this is unfortunately very easy to get wrong: given It helps to add a downcast method on |
I usually write |
Code description
By using
Any
as a supertrait, this feature enables quite nice conversions (upcasts and downcasts) between types in a 2-level depth trait-type taxonomy:outputs:
What worked well
This is much more ergonomic than asking each node to implement
as_any_ref
andas_any_mut
to enable downcasting.What worked less well
The
(node as &dyn Any).downcast_ref
syntax still looks a little cumbersome.The text was updated successfully, but these errors were encountered: