rust - Compact default generic declaration based on cfg - Stack Overflow

admin2025-04-20  4

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?

转载请注明原文地址:http://anycun.com/QandA/1745153111a90399.html