Match and Enums
Lesson 9 of 48 in Coddy's Rust for C Developers course.
A C enum names integer constants; associated data usually needs a separate struct or union plus discipline about the active tag. A Rust enum can store data directly in each variant, so the tag and its payload form one value. match examines that value with patterns. A pattern such as Sample::Ready(value) both selects a variant and binds its payload. Every possible variant must be covered; _ is a catch-all pattern. Unlike C switch, Rust arms do not fall through and need no break. A match can produce a value, and its arms must agree on the result type. The task supplies #[derive(Clone, Copy)] for an enum containing only integers; this lets small command values be copied when passed to more than one function.
C
#include <stdio.h>
enum State { OFFLINE, READY };
struct Sample { enum State state; int value; };
int main(void) {
struct Sample sample = { READY, 18 };
switch (sample.state) {
case OFFLINE: puts("offline"); break;
case READY: printf("sample=%d\n", sample.value); break;
}
return 0;
}Rust
enum Sample { Offline, Ready(i32) }
fn main() {
let sample = Sample::Ready(18);
match sample {
Sample::Offline => println!("offline"),
Sample::Ready(value) => println!("sample={}", value),
}
}A Rust data-carrying enum is not an arbitrary integer tag. Pattern matching accesses the payload belonging to the selected variant.
Challenge
EasyDecode 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));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for C Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap2Decisions and Loops
Boolean ConditionsIf ExpressionsMatch and EnumsLoops and RangesRecap: Charge Gate3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler