Menu
CoddyTech

Option and Matching

Lesson 25 of 48 in Coddy's Rust for C++ Developers course.

C++17 std::optional<T> distinguishes an engaged value from absence without reserving a sentinel in the value domain. Rust Option<T> has the variants Some(T) and None and serves the same modeling purpose. Some(0) is present, just as an engaged C++ optional containing zero is present. Rust options are not implicitly Boolean; use matching, an if let, or a predicate such as is_some. Unwrapping assumes presence and can panic, so a lookup with legitimate absence should handle both branches. An option can hold owned data or a borrowed reference depending on the API. Matching an owned non-copy payload can move it, whereas borrowing the option permits inspection while preserving its owner. The example locates an index, including index zero.

Complete standalone C++17 program:

#include <iostream>
#include <optional>
int main() {
    std::optional<int> slot = 0;
    if (slot) std::cout << "present:" << *slot << '\n';
    else std::cout << "missing\n";
}

Complete standalone Rust program:

fn main() {
    let values = [0, 5];
    match values.iter().position(|&n| n == 0) {
        Some(index) => println!("found:{}", index),
        None => println!("missing"),
    }
}
challenge icon

Challenge

Easy

Implement 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));
}
quiz iconTest yourself

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

All lessons in Rust for C++ Developers

Practice on your own: Online Rust compiler