Rust lang series episode #9 — enums (#rust-series)

in #rust-series8 years ago (edited)

Hello everyone, here is a new episode of Rust series. Today, we are going to talk about enumeration types in Rust.

Enums

Enum is enumeration type similar to enums in other languages. It represents one of several possible values called variants. In Rust enums are just little bit more powerful and there are multiple possibilities how enums can be used. Let's take a look at them.

Variants with no data

enum Switch {
  On,
  Off
}

Variants with unnamed data (like tupples)

enum Move {
    Left(i32),
    Right(i32),
    Up(i32),
    Down(i32)
}

Variants with named data (like strusts)

enum Change {
    None,
    Move {dx: i32, dy: i32}
}

Enum variables

Enum variables can have one of the variants values, they are assigned with :: because they are enum scoped.

let switch = Switch::On;
let move = Move::Up(10);
let change = Change::Move{x: 10, y: 0};

// don't forget to add #[derive(Debug)] before enum definittions
println!("{:?}", switch);
println!("{:?}", move);
println!("{:?}", change);

# output
On
Up(10)
Move { x: 10, y: 0 }

Evaluating with match

We can evaluate enum value by match statement

match switch {
    State::On => println!("on"),
    State::Off => println!("off")

# output
on
}

Getting sub-values

We can also access variant sub-values with certain destructuring in match expression, see the example:

match change {
    Change::Move{x, y} => println!("x: {}, y: {}", x, y),
    _ => panic!()
}

# output
x: 10, y: 0

Note: panic! macro causes application exit and prints panic message

As you can see enums are very practical and can be used in almost any Rust application.

Postfix

That's all for today, thanks for all appreciations, feel free to comment and point out possible mistakes (first 24 hours works the best but any time is fine). God bless your programming skills and stay tuned for next episodes.

Meanwhile you can also check the official documentation to find more about enums:

#rust-series
#rust-lang
#rust

Coin Marketplace

STEEM 0.25
TRX 0.20
JST 0.037
BTC 96006.08
ETH 3568.65
USDT 1.00
SBD 3.77