[フレーム]

Rust Enums


Enums

An enum (short for "enumeration") is a way to define a type that can be one of a few different values.

Each value in the enum is called a variant.

Enums are useful when you want to represent a value that can only be one of a set of options - like days of the week, directions, or results like success and error.


Create an Enum

To create an enum, use the enum keyword and add a set of named values (variants) separated by commas:

Example

enum Direction {
Up,
Down,
Left,
Right,
}

To use the enum, create a variable and assign it one of the enum's variants (use :: to access a variant):

Example

enum Direction {
Up,
Down,
Left,
Right,
}

fn main() {
let my_direction = Direction::Up;
println!("We are going up!");
}
Try it Yourself »

Match on Enum Values

Enums work great with the match statement. You can run different code depending on which variant is used:

Example

enum Direction {
Up,
Down,
Left,
Right,
}

fn main() {
let my_direction = Direction::Left;

match my_direction {
Direction::Up => println!("Going up"),
Direction::Down => println!("Going down"),
Direction::Left => println!("Going left"),
Direction::Right => println!("Going right"),
}
}
Try it Yourself »


Enums with Data

Enum variants can also hold data. This is useful when each variant needs to store extra information:

Example

enum LoginStatus {
Success(String),
Error(String),
}

fn main() {
let result1 = LoginStatus::Success(String::from("Welcome, John!"));
let result2 = LoginStatus::Error(String::from("Incorrect password"));

match result1 {
LoginStatus::Success(message) => println!("Success: {}", message),
LoginStatus::Error(message) => println!("Error: {}", message),
}
}
Try it Yourself »

Why Use Enums?

  • To group related values into one type
  • To make your code more readable and safe
  • To handle different cases with match

New

W3Schools Adventure App

Coding fundamentals as a game. Bite-sized lessons and challenges.

Ready to start your journey? Your streak is waiting.
+60 XP
W3Schools Adventure tutor
W3Schools Adventure map
×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

FORUM ABOUT ACADEMY
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

AltStyle によって変換されたページ (->オリジナル) /