Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[r+] Add enum discriminants to the reference. #21047

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/doc/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1413,6 +1413,27 @@ a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
In this example, `Cat` is a _struct-like enum variant_,
whereas `Dog` is simply called an enum variant.

Enums have a discriminant. You can assign them explicitly:

```
enum Foo {
Bar = 123,
}
```

If a discriminant isn't assigned, they start at zero, and add one for each
variant, in order.

You can cast an enum to get this value:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One last nit: you can only do this if the enum is C-like, i.e. none of the variants have any data attached. For example, you can't do None as u32.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C-like, i.e. none of the variants have any data attached.

By "C-like" you mean none like Foo(i32), yes? They all need to be Foo?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep! PR #20907 adds an intrinsic to extract he discriminant from any enum, but its only intended to be used as an optimization for things like PartialEq implementations.


```
# enum Foo { Bar = 123 }
let x = Foo::Bar as u32; // x is now 123u32
```

This only works as long as none of the variants have data attached. If
it were `Bar(i32)`, this is disallowed.

### Constant items

```{.ebnf .gram}
Expand Down