Crate fed [−] [src]
Anonymous, type-based, tagged type unions (here termed 'type federations') in stable Rust
Setup
In your crate root, include the crate aliased to _fed
(since you'll rely on the init_fed!
macro to declare the fed
module):
#[macro_use] extern crate fed as _fed;
Then, define all of the fed
traits in your crate with this macro call:
init_fed!();
To actually use a type federation, you'll need to implement the type federation traits for all
the concrete types you want to comprise the federation, via the fed!
macro:
use fed::*; fed!(String, bool, u8, Vec<i32>); fn main() { let var: Fed4<String, bool, u8, Vec<i32>> = 33.into(); assert!(var.is::<u8>()); }
For the time being, notice that we unfortunately will need to use
everything in the fed
module anywhere we want to use type federations. If this crate sees any use where this is an
issue, I might work on fixing that. But this is largely intended for prototyping the feature to
determine whether a fully fledged, built-in version would be useful for Rust to have.
Recursive types
Types like these could—for example—be useful for replacing much of the boilerplate used to express serialization formats like JSON and TOML.
// Wrapping ValueT in a newtype struct breaks the cyclic reference so that // we can make a recursive type. pub struct Value(pub ValueT); type ValueT = Fed3<i32, String, Array>; type Array = Vec<Value>; fed!( i32, String, Array, ); // (Would also want to implement utility traits like `Deref<Target=ValueT> for Value` and // `From<ValueT> for Value`.) let value = Value(123.into()); assert!((*value).is::<i32>());
Tidying instantiation up with a simple macro enables the following.
let ary = array![ 32, String::from("abc"), array![ String::from("nesting!"), array![], 8, ], 74, ]; assert!(ary[0].deref().is::<i32>()); assert_eq!(ary[1].as_ref().extract::<&String>().ok().unwrap(), "abc"); assert_eq!(ary[2].as_ref().extract::<&Array>().unwrap().len(), 3); assert!( ary[2] .as_ref() .extract::<&Array>() .unwrap() [0] .deref() .is::<String>() );
Macros
basic_fed | |
fed |
Macro to implement type federation traits for federations of concrete types |
fed2 | |
fed3 | |
fed4 | |
fed5 | |
fed6 | |
fed7 | |
fed8 | |
fed_promotion | |
fed_traits | |
from_fed | |
init_fed |
Setup macro to be called after including the fed crate |