DEV Community

RealACJoshua
RealACJoshua

Posted on

πŸš€ Rust Basics 5: Structs and Enums in Rust

Welcome back. This is the 5th post of our 7 post Rust tutorial.

Structs and enums are fundamental tools in Rust to organize and represent data. They make your code more readable, efficient, and expressive.

Step 1: What Are Structs?
A struct is like a blueprint for creating custom data types that group related information together.

Example: A Person Struct
Here’s how you define and use a struct:


struct Person {
    name: String,
    age: u8, // u8 means an unsigned 8-bit integer (0–255)
}

fn main() {
    // Create an instance of the Person struct
    let person = Person {
        name: String::from("Chisom"),
        age: 25,
    };

    // Access and print struct fields
    println!("Name: {}, Age: {}", person.name, person.age);
}

Enter fullscreen mode Exit fullscreen mode

Explanation
Defining a Struct:

struct Person defines the structure.
It has two fields: name (a string) and age (a number).

Creating an Instance:
Person { name: String::from("Chisom"), age: 25 } creates a Person instance.

Accessing Fields:
Use person.name and person.age to access the data.


Step 2: Adding Methods to Structs
You can add methods (functions) to structs to perform operations on their data.

Example: A Rectangle Struct with an area Method

struct Rectangle {
    width: u32,  // u32 means an unsigned 32-bit integer
    height: u32,
}

impl Rectangle {
    // Define a method to calculate area
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle { width: 10, height: 5 };
    println!("The area of the rectangle is: {}", rect.area());
}
Enter fullscreen mode Exit fullscreen mode

Explanation
impl Rectangle: Implements methods for the Rectangle struct.
fn area(&self): A method that calculates the area.
&self refers to the instance being used.
You call the method with rect.area().


Step 3: What Are Enums?
An enum represents a type that can have one of several predefined variants. Think of it as a way to describe "one thing out of many options."

Example: A Direction Enum

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

fn main() {
    let movement = Direction::Up;

    match movement {
        Direction::Up => println!("Going up!"),
        Direction::Down => println!("Going down!"),
        Direction::Left => println!("Going left!"),
        Direction::Right => println!("Going right!"),
    }
}

Enter fullscreen mode Exit fullscreen mode

Explanation
Defining an Enum:

enum Direction defines possible directions: Up, Down, Left, Right.
Using match:

match checks which variant is used and runs the corresponding code.
Each arm of match corresponds to a variant of the enum.


Step 4: Enums with Data

Enums can also hold data for each variant.

Example: A Message Enum

enum Message {
    Text(String),
    Number(i32),
}

fn main() {
    let msg = Message::Text(String::from("Hello"));

    match msg {
        Message::Text(text) => println!("Message: {}", text),
        Message::Number(num) => println!("Number: {}", num),
    }
}

Enter fullscreen mode Exit fullscreen mode

Explanation:
Each variant of Message can hold different types of data (String or i32).
match extracts the data inside the variant using patterns.
Practice for Today


Struct Practice:

Create a Car struct with fields for brand, model, and year.
Write a program to print a car's details.

Example:

struct Car {
    brand: String,
    model: String,
    year: u16,
}

fn main() {
    let car = Car {
        brand: String::from("Toyota"),
        model: String::from("Corolla"),
        year: 2020,
    };
    println!("{} {} ({})", car.brand, car.model, car.year);
}

Enter fullscreen mode Exit fullscreen mode

Enum Practice:

Create an enum Weather with variants Sunny, Rainy, and Cloudy.
Use match to print an appropriate message for each variant.

Example:

enum Weather {
    Sunny,
    Rainy,
    Cloudy,
}

fn main() {
    let today = Weather::Sunny;

    match today {
        Weather::Sunny => println!("It's a bright and sunny day!"),
        Weather::Rainy => println!("Don't forget your umbrella!"),
        Weather::Cloudy => println!("Looks like it might rain."),
    }
}

Enter fullscreen mode Exit fullscreen mode

πŸŽ‰ That’s it for RUST BASICS 5! You’ve learned Structs and Enums. In the next post, we’ll learn Functions and Error Handling in Rust.

Feel free to share your solutions or ask questions in the comments. Happy coding! πŸ¦€

Check out the Rust Documentation for more details.

Let me know if anything feels unclear!
Let me know how these examples feel, and if you'd like more exercises or clarification!

Top comments (0)