Option and Matching
Lesson 25 of 48 in Coddy's Rust for JavaScript Developers course.
In JavaScript, reading a missing array element or object property does not fail: it quietly produces undefined, and other code may use null for the same idea. Nothing forces a caller to check before using the value. Rust Option<T> makes presence a declared variant: Some carries a value and None carries none. Zero, false and empty text remain ordinary values when wrapped in Some; they are never confused with absence. The examples look up a nonexistent element and an existing zero, each with a fallback. Rust get borrows an existing element when present, so its result is an option containing a reference, and matching handles both cases without unchecked access. In JavaScript, ?? falls back only for null and undefined, but the common || habit also replaces valid falsy values such as 0. Rust has no universal null for ordinary references, and calling unwrap on None panics rather than supplying a default.
Complete standalone JavaScript program:
const samples = [0, 8];
console.log(samples[5]);
console.log(samples[5] ?? 99);
console.log(samples[0] || 99);
JavaScript output:
undefined
99
99
Complete standalone Rust program:
fn main() {
let samples = [0, 8];
println!("{:?}", samples.get(5));
println!("{}", match samples.get(5) { Some(n) => *n, None => 99 });
println!("{}", match samples.get(0) { Some(n) => *n, None => 99 });
}
Rust output:
None
99
0
Challenge
EasyImplement pub fn runner_up(values: &[i32]) -> Option<i32> in ranking.rs. Return the second-largest distinct value, or None when fewer than two distinct values exist. Duplicates do not create additional ranks. Do not mutate the caller's slice. Input contains zero or more whitespace-separated integers from -1000 to 1000. solve matches the API result and returns the number or none. The API must handle negative numbers and empty input without using a numeric sentinel for absence.
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, ranking.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 ranking;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
let values = vec![91, -6, 91, 18, 18];
assert_eq!(ranking::runner_up(&values), Some(18));
assert_eq!(ranking::runner_up(&[-21, -4, -9]), Some(-9));
assert_eq!(ranking::runner_up(&[]), None);
assert_eq!(ranking::runner_up(&[8, 8, 8]), None);
assert_eq!(ranking::runner_up(&[0, -1]), Some(-1));
assert_eq!(values, vec![91, -6, 91, 18, 18]);
// 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 JavaScript 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 Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record Readings6Absence and Failure
Option and MatchingResult and PropagationParsing and ValidationError ContractsFailure RecapPractice on your own: Online Rust compiler