2 ms·
> Rust has the "non_exhaustive" attribute that lets you declare that an enum might get more fields in the future.a Is there a reason, aside from documentation,
by KPGv2 2y ago
> Rust has the "non_exhaustive" attribute that lets you declare that an enum might get more fields in the future.a
Is there a reason, aside from documentation, that this is ever desirable? I rarely program in Rust, but why would this ever be useful in practice, outside of documentation? (Seems like code-as-documentation gone awry when your code is doing nothing but making a statement about future code possibilities)
- LegionMammal978 2y agoNormally, when you match on the value of an enum, Rust forces you to either add a case for every possible variant, or add a default arm "_ => ..." that acts as a 'none of the above' case. This is called exhaustiveness checking [0]. When you add #[non_exhaustive] to an enum, the compiler says to external users, "You're no longer allowed to just match every existing variant. You must always have a default 'none of the above' case when you're matching on this enum." This lets you add more variants in the future without breaking the API for existing users, since they all have a 'none of the above' case for the new variants to fall into. [0] https://doc.rust-lang.org/book/ch06-02-match.html#matches-are-exhaustive https://doc.rust-lang.org/book/ch06-02-match.html#matches-ar...
- jeroenhd 2y agoIf your library processes data from another language, you'll probably need to deal with the possibility that the library returns open ended enums. I believe I've also seen this declaration for generated bindings for a JSON API that promises backwards compatibility for calls and basic functionality at least. Future versions may include more options, but the code will still compile fine against the older API. I don't think it's a great tool to use everywhere, but there are edge cases where Rust's demand for exhaustive matches conflicts with the non-Rust world, and that's where stuff like this becomes hard to avoid.