Expand description
§::named-generics-bundle
Convenience macros to help with the “bundle multiple generic params with a helper trait” pattern
§API summary
#[named_generics_bundle]
trait SomeTrait {
type SomeAssocType: SomeBounds + Clone;
}
fn some_api<S: SomeTrait>(nameable: S::SomeAssocType) {
// Properly implied bounds.
nameable.clone();
}
/// We shall have `Example: SomeTrait + Sized + AllStdDeriveTraits`
type Example = SomeTrait![
SomeAssocType = ...,
];
some_api::<Example>(
// …,
);
// or, directly:
some_api::<SomeTrait![SomeAssocType = i32]>(42);§Motivation
Click to show
As your Rust projects grows in scope and functionality, your generic types may end up with more and more generic parameters:
#[derive(Debug)]
struct Device<Fuel, Engine, Output>
where
Fuel: Burns,
Engine: YieldsEnergy,
Output: EnergyForm,
{
fuel: Fuel,
engine: Engine,
_p: PhantomData<fn() -> Output>,
}
impl<Fuel, Engine, Output> Device<Fuel, Engine, Output>
where
// 1. First problem: repeat these bounds on every usage of `Device`. So WET… 💦
Fuel: Burns,
Engine: YieldsEnergy,
Output: EnergyForm,
{
pub fn assemble(fuel: Fuel, engine: Engine) -> Self {
Self { fuel, engine, _p: PhantomData }
}
pub fn frobnicate(&mut self) -> Output {
self.engine.yield_energy(&mut self.fuel)
}
}
fn get_away_from_the_beam() -> ! {
// 2. Second problem: index/position-based generics "tuples"…
// 😵💫 which one was going second again? 😵💫
let mut device = Device::<Uranium, FluxCapacitor, Beam>::assemble(
// …
);
let beam: Beam = device.frobnicate();
match beam {}
}It turns out, you can make this already significantly more convenient from the point of view of the callee by using a helper trait to bundle all the generic parameters as associated types, and making the callees generic only over that helper trait.
pub trait DeviceSetup {
//! Define your generic bounds *ONCE*. So 🌵 DRY 🐪 🌵
type Fuel: Burns;
type Output: EnergyForm;
type Engine: YieldsEnergy;
}
#[derive(Debug)]
struct Device<S: DeviceSetup> {
fuel: S::Fuel,
engine: S::Engine,
}
impl<S: DeviceSetup> Device<S> {
pub fn assemble(fuel: S::Fuel, engine: S::Engine) -> Self {
Self { fuel, engine }
}
pub fn frobnicate(&mut self) -> S::Output {
self.engine.yield_energy(&mut self.fuel)
}
}
fn get_away_from_the_beam() -> ! {
// No more index/position-based generics "tuples". Get _named_ generic entries.
// So robust to misordering. Much readability.
enum BlackMesaStyle {}
impl DeviceSetup for BlackMesaStyle {
type Fuel = Uranium;
type Engine = FluxCapacitor;
type Output = Beam;
}
let mut device = Device::<BlackMesaStyle>::assemble(
// …
);
let beam: Beam = device.frobnicate();
match beam {}
}This is already quite a useful trick, but it comes with certain caveats:
-
The most notable one, is that you can no longer inline-turbofish the generics: it is necessary to define a helper type, and this can get unwieldy when there are outer generic parameters in scope.
-
There are also some secondary issues, such as slapping
#[derive(Clone)]on thestruct Engineand this resulting inOutputhaving to be clone, even though it is not part of the actual fields ofEngine(it is a mere dummyPhantomDatainstead).- To be fair, this is a limitation/bug stemming from
#[derive(Clone)]itself, and other similar stdlib#[derive()]s, being rather dumb w.r.t. theimpls they generate, w.r.t. adding unnecessary bounds on the params themselves rather than focusing on bounding the field types (there is a desire to do the latter, called “perfect derives”, but they only want to do so once all edge cases, such as recursive types, can be handled. There are also some “implicit SemVer” considerations involved as well).
So you:
- either make
Output : Cloneeven if the only thing susceptible of being.clone()d is theDevice, - or you stop using
#[derive(Clone)], and manuallyimplthe trait in question. Which is quite cumbersome! Or you involve some third-party lib to help you with that in a smarter or at least more tweakable manner than the stdlib, such as::derivative(but this is a rather old crate, nowadays, and most people feel like it is unnecessary to add a dependency for such a small thing).
- To be fair, this is a limitation/bug stemming from
Enters this crate!
§Detailed Example
#[::named_generics_bundle::named_generics_bundle] // 👈 1. Add this…
pub trait DeviceSetup {
//! Define your generic bounds *ONCE*. So 🌵 DRY 🐪 🌵
type Fuel: Burns;
type Output: EnergyForm;
type Engine: YieldsEnergy;
}
#[derive(Debug)]
struct Device<S: DeviceSetup> {
fuel: S::Fuel,
engine: S::Engine,
}
impl<S: DeviceSetup> Device<S> {
pub fn assemble(fuel: S::Fuel, engine: S::Engine) -> Self {
Self { fuel, engine }
}
pub fn frobnicate(&mut self) -> S::Output {
self.engine.yield_energy(&mut self.fuel)
}
}
fn get_away_from_the_beam() -> ! {
// No more index/position-based generics "tuples". Get _named_ generic entries.
// So robust to misordering. Much readability.
type BlackMesaStyle = DeviceSetup![ // 👈 2. …so you get access to this
Fuel = Uranium,
Engine = FluxCapacitor,
Output = Beam,
];
let mut device = Device::<BlackMesaStyle>::assemble(
// …
);
let beam: Beam = device.frobnicate();
match beam {}
}
enum Cake {}
struct TestSubject {}
impl Burns for TestSubject {}
fn the_cake_is_a_lie() -> ! {
let testing_chamber =
// 👇 3. It can also be turbofished-inlined!
Device::<DeviceSetup![
Engine = HandheldPortalDevice,
Output = Cake,
Fuel = TestSubject,
]>::assemble(
// …
)
;
let puzzle_solved: Cake = testing_chamber.frobnicate();
match puzzle_solved {}
}See the docs of #[named_generics_bundle] for more info.
Attribute Macros§
- named_
generics_ bundle - Main macro, entrypoint to the features of the crate.