Menu
CoddyTech

Match and Enums

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

JavaScript has no enum type. A common pattern is a plain object with a string tag such as kind, inspected with switch or if. Nothing checks those tags: a misspelled tag matches no case, the function runs off its end, and the caller receives undefined with no error. A forgotten break can also fall through into the next case. A Rust enum declares every variant up front, and each variant states its payload, such as Ready(u32). A value holds exactly one variant, and you cannot build one that the declaration does not list. A match must cover every variant, by name or with the catch-all pattern _, so a missing case is a compile error rather than a silent undefined. Each arm is an expression, the whole match produces a value, and arms never fall through. A pattern such as DocumentState::Ready(pages) both tests the variant and binds its payload to a new name. The examples describe a document state; the third JavaScript call uses a misspelled tag.

Complete standalone JavaScript program:

function describe(state) {
  switch (state.kind) {
    case "ready":
      return `pages=${state.pages}`;
    case "loading":
      return "loading";
  }
}
console.log(describe({ kind: "ready", pages: 9 }));
console.log(describe({ kind: "loading" }));
console.log(describe({ kind: "redy", pages: 9 }));

JavaScript output:

pages=9
loading
undefined

Complete standalone Rust program:

enum DocumentState { Ready(u32), Loading }
fn describe(state: DocumentState) -> String {
    match state {
        DocumentState::Ready(pages) => format!("pages={}", pages),
        DocumentState::Loading => "loading".to_string(),
    }
}
fn main() {
    println!("{}", describe(DocumentState::Ready(9)));
    println!("{}", describe(DocumentState::Loading));
}

Rust output:

pages=9
loading
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 JavaScript Developers

Practice on your own: Online Rust compiler