downcast-rs
Rust enums are great for types where all variations are known beforehand. But in the case where you want to implement a container of user-defined types, an open-ended type like a trait object is needed. In some cases, it is useful to cast the trait object back into its original concrete type to access additional functionality and performant inlined implementations.
downcast-rs
adds basic downcasting support to trait objects, supporting type
parameters, associated types, and constraints.
To make a trait downcastable, make it extend the downcast::Downcast
trait and
invoke impl_downcast!
on it as follows:
impl_downcast!;
// With type parameters.
impl_downcast!;
// With associated types.
impl_downcast!;
// With constraints on types.
impl_downcast!;
// With concrete types.
impl_downcast!;
impl_downcast!;
Example without generics
extern crate downcast_rs;
use Downcast;
// To create a trait with downcasting methods, extend `Downcast` and run
// impl_downcast!() on the trait.
impl_downcast!;
// Concrete types implementing Base.
;
;
Example with a generic trait with associated types and constraints
extern crate downcast_rs;
use Downcast;
// To create a trait with downcasting methods, extend `Downcast` and run
// impl_downcast!() on the trait.
impl_downcast!;
// or: impl_downcast!(concrete Base<u32> assoc H=f32)
// Concrete types implementing Base.
;
;
License
Copyright 2015, Ashish Myles. This software is dual-licensed under the MIT and Apache 2.0 licenses.