If Expressions
Lesson 8 of 48 in Coddy's Rust for PHP Developers course.
PHP uses a ternary expression to select between values, while an ordinary if statement controls execution. Rust if itself produces a value, letting compatible branch results initialize a binding. The examples select moon using text equality rather than relying on truthiness. PHP strict equality checks both type and value; Rust string equality follows its typed contract. Rust returns the final expression of a branch only when it has no semicolon. A semicolon discards that expression and leaves unit, potentially conflicting with the other branch. Account for both outcomes in a value-producing Rust if, and use an explicit enum when outcomes need different data shapes.
PHP: complete program
<?php
declare(strict_types=1);
$mode = "night";
$icon = $mode === "night" ? "moon" : "sun";
echo $icon, "\n";
Rust: complete program
fn main() {
let mode = "night";
let icon = if mode == "night" { "moon" } else { "sun" };
println!("{}", icon);
}A semicolon after the intended Rust branch value changes its result into unit.
Challenge
EasyCalculate 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));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for PHP 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