Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rust
enum
enumeration
rust basics

What is categorization with enumerations in Rust?

Marvah Mushtaq

Enum in Rust

An enum in Rust is a custom data type representing data that can be any kind among several possible variants. Each variant in the enum can optionally have data associated with it. An enumerated type is defined using the enum keyword before the name of the enumeration. It also consists of methods.

Empty enum

Empty enums are similar to ! and can never be instantiated. They are used mainly to mess with the type system in interesting ways.

Fieldless enums

The simplest form of enum is one where none of the variants have any fields, a fieldless enum.

fn main() {
enum SomeEnum {
  Variant1,
  Variant2,
  Variant3,
}
}

Fieldless enums may also specify the value of their discriminants explicitly.

fn main() {
enum SomeEnum {
  Variant22 = 22,
  Variant44 = 44,
  Variant45,
}
}

Data-carrying enums

Enums with at least one variant with fields are called data-carrying enums. Note that for this definition, it is not relevant whether the variant fields are zero-sized.

fn main() {
enum Foo {
  Bar(()),
  Baz,
}
}

RELATED TAGS

rust
enum
enumeration
rust basics

CONTRIBUTOR

Marvah Mushtaq
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring