avatarJohn Philip

Summary

The web content provides a detailed solution and explanation for the enums2.rs challenge from the Rustlings series, focusing on the use of Rust enums and pattern matching.

Abstract

The article is the thirty-third installment of the Rustlings series, dedicated to solving the enums2.rs exercise from the Rustlings repository. It explains how to define an enum called Message with various variants, each capable of holding different types of associated data. The challenge involves resolving compiler errors by correctly defining enum variants and implementing a call method to demonstrate how enums can encapsulate both data and behavior. The solution walkthrough is accompanied by an explanation of the key concepts of Rust enums, their similarity to algebraic data types in functional languages, and the use of pattern matching to handle different enum variants. The article also encourages readers to experiment with the code on the Rust Playground and shares resources for further reading on enums and pattern syntax in Rust.

Opinions

  • The author emphasizes the versatility and capability of Rust enums for representing different types of messages or data.
  • Enums in Rust are praised for their ability to model various scenarios effectively, making them a powerful feature of the language.
  • The article suggests that understanding how to create enums in Rust and define different variants is a key takeaway for readers.
  • The importance of pattern matching in conjunction with enums is highlighted as a feature that simplifies running different code for different values of an enumeration.
  • The author invites readers to contribute to the Rustaceans community by sharing their knowledge and expertise in Rust.
  • The value of the article is underscored by the call to action for readers to follow the publication and share the article, indicating its perceived educational benefit.

Rustlings: enums2.rs #Issue33 — Enums in Rust

Rustlings Challenge: enums2.rs Solution Walkthrough

Image by serokell.io

This is the thirty-third (33rd) issue of the Rustlings series. In this issue, we provide solutions to Rustlings exercises along with detailed explanations. In this issue we will solve the challenge on enums2.rs.

Previous challenge #Issue 32

Rust allows you to define types called “enums” which enumerate possible values. Enums are a feature in many languages, but their capabilities differ in each language. Rust’s enums are most similar to algebraic data types in functional languages, such as F#, OCaml, and Haskell. Useful in combination with enums is Rust’s “pattern matching” facility, which makes it easy to run different code for different values of an enumeration.

Challenge:

// enums2.rs
//
// Execute `rustlings hint enums2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

#[derive(Debug)]
enum Message {
    // TODO: define the different variants used below
}

impl Message {
    fn call(&self) {
        println!("{:?}", self);
    }
}

fn main() {
    let messages = [
        Message::Move { x: 10, y: 30 },
        Message::Echo(String::from("hello world")),
        Message::ChangeColor(200, 255, 255),
        Message::Quit,
    ];

    for message in &messages {
        message.call();
    }
}

If you run the code on your editor, the compiler will throw the error:

Compiling playground v0.0.1 (/playground)
error[E0599]: no variant named `Move` found for enum `Message`
  --> src/main.rs:21:18
   |
9  | enum Message {
   | ------------ variant `Move` not found here
...
21 |         Message::Move { x: 10, y: 30 },
   |                  ^^^^ variant not found in `Message`

error[E0599]: no variant or associated item named `Echo` found for enum `Message` in the current scope
  --> src/main.rs:22:18
   |
9  | enum Message {
   | ------------ variant or associated item `Echo` not found for this enum
...
22 |         Message::Echo(String::from("hello world")),
   |                  ^^^^ variant or associated item not found in `Message`

error[E0599]: no variant or associated item named `ChangeColor` found for enum `Message` in the current scope
  --> src/main.rs:23:18
   |
9  | enum Message {
   | ------------ variant or associated item `ChangeColor` not found for this enum
...
23 |         Message::ChangeColor(200, 255, 255),
   |                  ^^^^^^^^^^^ variant or associated item not found in `Message`

Explanation:

In the challenge enums1.rs, the task was to define an enum named Message with several variants, such as Quit, Echo, Move, and ChangeColor. The key takeaway from this challenge is understanding how to create enums in Rust and define different variants.

In the challenge enums2.rs, we are needed to define variants for the Message enum, each with specific associated data types. This exercise demonstrates how to use enums to represent different types of messages or data in your Rust programs. It also introduced the concept of implementing methods for enums, making them more versatile and capable of performing actions.

Solution:

#[derive(Debug)]
enum Message {
    // TODO: define the different variants used below
    Move{x:u32,y:u32},
    Echo(String),
    ChangeColor(u32,u32,u32),
    Quit,
}

impl Message {
    fn call(&self) {
        println!("{:?}", self);
    }
}

fn main() {
    let messages = [
        Message::Move { x: 10, y: 30 },
        Message::Echo(String::from("hello world")),
        Message::ChangeColor(200, 255, 255),
        Message::Quit,
    ];

    for message in &messages {
        message.call();
    }
}

Overall, these challenges highlight the power of enums in Rust for creating custom types with distinct variants and associated data, which can be useful for modeling various scenarios in your code.

You can experiment with the code on Rust Playground.

Resources

Before you go

Thank you for taking the time to read through this challenge. We invite you to share your knowledge of Rust as well. If you found this article valuable, please don’t hesitate to share it with others. Don’t forget to follow the publication and give the article some claps 👏.

Thank you, and we look forward to seeing you for the next challenges!

More reads

Rust
Rustlang
Rustling
Programming
Software Development
Recommended from ReadMedium