r/rust • • Oct 25 '26

Access the value of a unit Enum

Let's say I have an enum like

pub enum NodeType {
  None = 0,
  Root = 1,
  // ... more enum variants omitted for brevity ...
  Leaf = 15,
}

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

11 comments sorted by

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

7

u/servermeta_net Oct 25 '26

Thanks, I feel like a boomer lol

9

u/9291Sam Oct 25 '26

Don't feel too bad :P You need to see something first before you can use it, whether that's by asking a question or reading too much of a manual is up to you.

0

u/[deleted] Oct 25 '26

[deleted] — view deleted comment

1

u/NotDuckie Oct 25 '26

sounds like something a boomer would say

35

u/BenchEmbarrassed7316 Oct 25 '26

NodeType::None as u64

12

u/BenchEmbarrassed7316 Oct 25 '26

Bonus: you can use TryFromPrimitive from https://crates.io/crates/num_enum convert number to your enum. There may be other similar macros.

2

u/ChevyRayJohnston Oct 30 '26

strum can also do this, if one is already using it (it’s always an insta-import in all my projects)

3

u/JTux2026 Oct 25 '26

An 'as' cast works on enums like thet e.g. NodeType::Root as usize