codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🦀

Rust

18 / 58 topics
17Structs18Enums
Tutorials/Rust/Enums
🦀Rust

Enums

Updated 2026-05-15
10 min read

Enums

Introduction

In Rust, an enum (short for enumeration) is a powerful data structure that allows you to define a type by enumerating its possible variants. Enums are incredibly useful when you need to represent a value that can be one of several distinct types. This tutorial will guide you through the basics of enums and how they can be used in Rust.

Concept

An enum in Rust is defined using the enum keyword followed by the name of the enum and its variants. Each variant can optionally hold data, making enums a versatile tool for modeling complex data structures.

Basic Syntax

Here's the basic syntax for defining an enum:

enum TrafficLight {
    Red,
    Yellow,
    Green,
}

In this example, `TrafficLight` is an enum with three variants: `Red`, `Yellow`, and `Green`. Each variant is a distinct value of type `TrafficLight`.

### Variants with Data

You can also define variants that hold data. This is done by associating each variant with one or more fields:

```rust
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

In this example:
- `Quit` has no data associated with it.
- `Move` contains an anonymous struct with two fields: `x` and `y`.
- `Write` contains a single `String`.
- `ChangeColor` contains three `i32` values.

### Using Enums

To use an enum, you can create instances of its variants:

```rust
let light = TrafficLight::Red;
let message = Message::Move { x: 10, y: 20 };

You can also match against enums using the `match` keyword. This is a powerful feature that allows you to handle each variant differently:

```rust
fn print_light(light: TrafficLight) {
    match light {
        TrafficLight::Red => println!("Stop!"),
        TrafficLight::Yellow => println!("Caution!"),
        TrafficLight::Green => println!("Go!"),
    }
}

print_light(TrafficLight::Red); // Output: Stop!

The Option Enum

Rust's standard library includes a special enum called Option, which is used to represent the presence or absence of a value. It has two variants:

enum Option<T> {
    Some(T),
    None,
}

This is commonly used in functions that may not return a value, such as searching for an item in a collection.

Examples

Example 1: Basic Enum Usage

Let's create a simple program that uses enums to represent different types of shapes and calculate their areas:

enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
    Square(f64),
}

fn area(shape: &Shape) -> f64 {
    match shape {
        Shape::Circle(radius) => 3.14 * radius * radius,
        Shape::Rectangle(width, height) => width * height,
        Shape::Square(side) => side * side,
    }
}

fn main() {
    let circle = Shape::Circle(5.0);
    let rectangle = Shape::Rectangle(4.0, 6.0);
    let square = Shape::Square(3.0);

    println!("Area of circle: {}", area(&circle)); // Output: Area of circle: 78.5
    println!("Area of rectangle: {}", area(&rectangle)); // Output: Area of rectangle: 24
    println!("Area of square: {}", area(&square)); // Output: Area of square: 9
}

Example 2: Using Enums with Option

Here's an example that demonstrates how to use the Option enum:

fn find_number(numbers: &[i32], target: i32) -> Option<usize> {
    for (index, &number) in numbers.iter().enumerate() {
        if number == target {
            return Some(index);
        }
    }
    None
}

fn main() {
    let numbers = [10, 20, 30, 40, 50];
    match find_number(&numbers, 30) {
        Some(index) => println!("Number found at index: {}", index), // Output: Number found at index: 2
        None => println!("Number not found"),
    }
}

In this example, the find_number function returns an Option<usize>. If the number is found, it returns Some(index), otherwise it returns None.

What's Next?

Now that you have a good understanding of enums in Rust, you can explore more advanced topics such as modules. Modules help organize your code into logical groups and manage dependencies between different parts of your program.

In the next section, we'll dive deeper into how to use modules to structure larger Rust projects effectively.


PreviousStructsNext Modules

Recommended Gear

StructsModules