Compact default generic declaration based on cfg

PressRex profile image
by PressRex
Compact default generic declaration based on cfg

I'm writing an allocator aware vector variant (where .push() actually returns Result, because allocation may fail). So I have a code like this:

pub struct DynamicArray<T, TAllocator> where
    TAllocator: Allocator

So far so good. Now I don't want users to always specify TAllocator, I have a default implementation called StdAllocator. Normally I would do:

pub use [something something]::StdAllocator;

pub struct DynamicArray<T, TAllocator=StdAllocator> where
    TAllocator: Allocator

except the entire crate is ![no_std] and in order to have StdAllocator a specific feature, called std_alloc has to be enabled. This leads to the following code:

#[cfg(feature="std_alloc")]
pub use [something something]::StdAllocator;

pub struct DynamicArray<T,
    #[cfg(feature="std_alloc")] TAllocator=StdAllocator,
    #[cfg(not(feature="std_alloc"))] TAllocator,
> where
    TAllocator: Allocator

which is ugly and not ergonomic. Is it possible to reduce the struct declaration to something like:

pub struct DynamicArray<T,
    TAllocator #[cfg(feature="std_alloc")]=StdAllocator
> where
    TAllocator: Allocator

The above of course doesn't compile, but I'm looking for something like this, that will reduce the boilerplate. Or do I have to write some proc_macro manually?

Source: View source

PressRex profile image
by PressRex

Subscribe to New Posts

Lorem ultrices malesuada sapien amet pulvinar quis. Feugiat etiam ullamcorper pharetra vitae nibh enim vel.

Success! Now Check Your Email

To complete Subscribe, click the confirmation link in your inbox. If it doesn’t arrive within 3 minutes, check your spam folder.

Ok, Thanks

Read More