Rust course Lesson 5 of 6

Rust from zero: an enum names the cases

An enum lists the shapes a value can have. Paid is Yes with the cents, or No. The program prints paid 450 and unpaid.

Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.

Back to top

Some values are one of a few shapes. An order is paid, and the payment carries the cents, or it is unpaid and there is no amount to read. An enum lists those shapes. match then has to handle every shape. You cannot read the cents that only exist in Yes without saying what happens on No.

The match has to cover the cases#

An enum is a value that is exactly one of its variants. Paid::Yes carries an i32, the cents that were paid. Paid::No carries nothing. match is how you take the value apart, and the compiler requires an arm for every variant. Inside the Yes arm the name cents is the carried integer. Inside the No arm there is no integer to read. You cannot forget a case and discover it in production. This program builds both values and prints both lines.

Yes carries the cents, No does not
  1. Yes(450)armpaid 450
  2. Noarmunpaid
enum Paid {
    Yes(i32),
    No,
}

fn read(a: Paid) -> String {
    match a {
        Paid::Yes(cents) => format!("paid {cents}"),
        Paid::No => "unpaid".to_string(),
    }
}

fn main() {
    println!("{}", read(Paid::Yes(450)));
    println!("{}", read(Paid::No));
}
paid 450
unpaid

The data lives in the case#

Yes(i32) carries the cents. No carries nothing. Paid::Yes(450) is a value of type Paid, not an i32. read takes the enum and matches. The Yes arm binds the number to cents and builds paid 450. The No arm returns the text unpaid.

Delete the No arm and the program does not compile. The compiler lists the case you skipped. That is the advantage over a string flag. A typo in "yes" would compile and do the wrong thing. A typo in Paid::Yes does not compile.

Both cases return text#

read always returns a String, so the caller does not check which arm ran. The difference is inside read, where the data is actually there. A receipt can print paid 450 or unpaid without a second type. The next lesson names a method in a trait so a function can call it on more than one struct.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.