Menu
CoddyTech

If Expressions

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

In JavaScript, if is a statement, so choosing a value usually means the conditional operator ? :, often nested for three cases. Rust has no conditional operator because if is itself an expression: a binding can receive the value of the selected branch, and else if chains read top to bottom. A JavaScript conditional can return a string from one branch and a number from the other, because each value carries its own type at runtime. Both Rust branches must produce one compatible type, checked even for the branch that never runs. The last expression in a Rust block has no trailing semicolon when its value is needed. A semicolon turns that final expression into a statement whose block value is unit, written (). The examples classify a temperature reading into one of three labels, then print it once. This separates selection from output and makes branch types easy to see. A Rust if used only for side effects need not have an else, but a value-producing choice needs every path covered.

Complete standalone JavaScript program:

const reading = 18;
const label = reading < 10 ? "cold" : reading <= 25 ? "mild" : "hot";
console.log(label);

JavaScript output:

mild

Complete standalone Rust program:

fn main() {
    let reading = 18;
    let label = if reading < 10 {
        "cold"
    } else if reading <= 25 {
        "mild"
    } else {
        "hot"
    };
    println!("{}", label);
}

Rust output:

mild
challenge icon

Challenge

Easy

Calculate delivery charges. Input is a distance from 0 to 1000 kilometers. Required API: pub fn charge(distance: u32) -> u32 returns 0 for distance zero, 5 for distances 1 through 3, and 5 + 2 * (distance - 3) for longer distances. pub fn band(distance: u32) -> &'static str returns none, local, or extended for those same three cases. Output band:charge. The returned labels are string literals, so &'static str is supplied in the starter. Implement the public API in delivery.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, delivery.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 delivery;
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!(delivery::charge(2), 5);
assert_eq!(delivery::band(2), "local");
assert_eq!(delivery::charge(0), 0);
assert_eq!(delivery::band(0), "none");
assert_eq!(delivery::charge(3), 5);
assert_eq!(delivery::band(3), "local");
assert_eq!(delivery::charge(17), 33);
assert_eq!(delivery::band(17), "extended");
assert_eq!(delivery::charge(2), 5);
    // 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