Menu
CoddyTech

Match and Enums

Lesson 9 of 48 in Coddy's Rust for Java Developers course.

Java enums define a closed set of named constants. Rust enums also define alternatives, and each variant can additionally carry its own data. Here the variants have no payload so the comparison with a Java enum is direct. Rust match checks alternatives and yields the selected arm's value. Arms use =>, and exhaustive matching means every possible value must be handled.

Java 17 switch expressions can also be exhaustive for enums. Rust patterns extend beyond constant labels to destructuring enum payloads, tuples and other structures. A wildcard _ handles all remaining values, but can hide a newly added variant that deserves separate treatment. Prefer explicit arms when each variant has a distinct meaning. Rust enum alternatives are values of one enum type, not subclasses in an inheritance tree.

Java: complete program

class Main {
    enum Shade { RED, BLUE }
    public static void main(String[] args) {
        Shade s = Shade.BLUE;
        String mood = switch (s) { case RED -> "warm"; case BLUE -> "cool"; };
        System.out.println(mood);
    }
}

Rust: complete program

#[derive(Clone, Copy)]
enum Shade { Red, Blue }
fn main() {
    let shades = [Shade::Red, Shade::Blue];
    let mood = match shades[1] { Shade::Red => "warm", Shade::Blue => "cool" };
    println!("{}", mood);
}

Pitfall: a Rust match arm does not fall through into the next arm and needs no Java-style break.

challenge icon

Challenge

Easy

Decode one actuator command. Input is forward amount, back amount, or wait; amounts are integers from 0 to 1000. Required public enum: Command with variants Forward(i32), Back(i32), and Wait. Required API: pub fn displacement(command: Command) -> i32 returns the amount for Forward, its negation for Back, and zero for Wait. pub fn active(command: Command) -> bool returns false only for Wait, even when a movement amount is zero. The enum derives Clone, Copy so the supplied wrapper can pass the same command to both functions. Output displacement active. Implement the public API in actuator.rs. The supplied exercise.rs parses valid input and calls that API. Return the specified text without a trailing newline; the locked driver adds one newline. Do not print from the API. All input values satisfy the stated bounds.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, actuator.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod actuator;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
assert_eq!(actuator::displacement(actuator::Command::Forward(37)), 37);
assert_eq!(actuator::displacement(actuator::Command::Back(37)), -37);
assert_eq!(actuator::displacement(actuator::Command::Wait), 0);
assert!(actuator::active(actuator::Command::Forward(0)));
assert!(actuator::active(actuator::Command::Back(0)));
assert!(!actuator::active(actuator::Command::Wait));
assert_eq!(actuator::displacement(actuator::Command::Forward(37)), 37);
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Java Developers

Practice on your own: Online Rust compiler