External Publication
Visit Post

[Pre-RFC] Allow attributes to be applied to generic arguments

Rust Internals [Unofficial] March 26, 2026
Source

Currently, rust allows the following.

struct MyStruct<#[cfg(feature)] Arg>();

This is useful in certain circumstances. For instance, suppose you wanted to make a crate with a custom collection. If the allocator_api was enabled, you could automatically support it in your struct.

struct MyCollection<#[cfg(feature = "allocator_api")] A: Allocator>{
    // ..
    alloc: A
}

You can even use it in impl blocks:

impl<#[cfg(feature)] Arg> MyStruct

What you can't do, however, which makes the above nearly pointless, and what I want to change, is the following

impl<#[cfg(feature)] Arg> MyStruct<#[cfg(feature)] Arg>

This results in the error attributes cannot be applied to generic arguments

This has been a major headache for crate developers in the past. In many cases, the choice is between essentially duplicating all relevant code (I've seen recommendations to create duplicate modules that have identical-other-than-this code), choosing to whether to support nightly or stable, or evil macro hacks. (1) (2) (3)

As far as I know, implementing this shouldn't be too hard,as it would be quite similar to the current way the other inline attributes work. I think this would be a major ergonomics improvement for implementing collection crates.

(P. S. I searched, but if I missed a prior conversation where this option was discussed and rejected, I apologize. The pr that created that error was simply consolidating that error from a generic syntax error)

Discussion in the ATmosphere

Loading comments...