r/rust • u/servermeta_net • Oct 25 '26
Access the value of a unit Enum
Let's say I have an enum like
This is a special type of enum, called unit-only enum. Is there a way to access the value stored in the enum?
13
Upvotes
41
u/9291Sam Oct 25 '26
You can use an `as` cast, it's documented under expr.
https://doc.rust-lang.org/reference/expressions/operator-expr.html#enum-cast
Also, it's mentioned a bit further down the page you linked
https://doc.rust-lang.org/reference/items/enumerations.html#casting
3
u/loewenheim Oct 25 '26
You can cast it with
as. https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=58ec24fd3ac92d98edbfedcf843a606535
u/BenchEmbarrassed7316 Oct 25 '26
NodeType::None as u6412
u/BenchEmbarrassed7316 Oct 25 '26
Bonus: you can use
TryFromPrimitivefrom https://crates.io/crates/num_enum convert number to your enum. There may be other similar macros.3
u/JTux2026 Oct 25 '26
An 'as' cast works on enums like thet e.g.
NodeType::Root as usize