How does Option<T> optimizations work?

Let T be some type, struct or enum. How does Option<T> know when T has some un-used bit patterns, and thus Option<T> can have the same size as T ?

T defines a niche.

You can make your own on nightly, but I couldn't even find a tracking issue (and the rustc prefix highlights that this is a rustc implementation detail), so I don't know that I'd want to rely on it. You can also search GitHub for a number of ICEs related to those attributes.

Edit: But beware that niches can also be disabled when nested inside certain other things.


^^ there is no tracking issue as it's a compiler internal. I brought this up on Zulip a couple weeks ago and consensus was to not expose anything like those attributes directly. Definitely don't use them as an end user unless absolutely necessary.

1 Like

Interesting. So that means there's a consensus to not have "user defined niches" generally (vs rustc_layout_* specifically)? That's surprisingly to me -- I can't recall much else where the decision was to (a) not aim for giving users of the language the ability to do it themselves in a sanctioned manner and (b) in-practice promote a compiler-specific extension.

I don't think that's the consensus. The consensus, as I understand it, is that it won't happen via attributes that look like those ones.

Here's the most recent conversation I remember about it:


Thanks, it seems I misinterpreted "anything like those attributes".

1 Like

Yeah, my wording may not have been the best. But that is the thread I was referring to (given that I started it).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.