ndtestrs / src/main.rs

raw file 1083 bytes
use std::io::{self, BufRead, Write};

fn main() {
    // 1. Basic function with a typed return value
    let squares = square_sums(3, 4);
    println!("3² + 4² = {squares}");

    // 2. match with pattern binding
    let status = get_status();
    match status {
        200 => println!("Status: OK"),
        404 => println!("Status: Not Found"),
        code => println!("Status: unknown code {code}"),
    }

    // 3. Read a name from stdin and greet it.
    // Flush stdout after printing the prompt, otherwise the "Enter your
    // name:" text is buffered and only appears AFTER the user hits Enter.
    let stdout = io::stdout();
    let mut handle = stdout.lock();
    handle.write_all(b"Enter your name: ").unwrap();
    handle.flush().unwrap();
    let mut name = String::new();
    io::stdin().lock().read_line(&mut name).unwrap();
    let name = name.trim();
    println!("Hello, {name}!");
}

/// Sum of squares of two numbers.
fn square_sums(a: i32, b: i32) -> i32 {
    a * a + b * b
}

/// A little pretend "status code" lookup.
fn get_status() -> i32 {
    200
}