Switch in Rust

Here’s a translation of the provided code and explanations to Rust:

Switch statements express conditionals across many branches.

use std::fmt;
use chrono::{Datelike, Timelike, Utc};

fn main() {
    let i = 2;
    print!("Write {} as ", i);
    match i {
        1 => println!("one"),
        2 => println!("two"),
        3 => println!("three"),
        _ => (),
    }

    // Combinations of match cases with commas and an optional default case.
    match Utc::now().weekday() {
        chrono::Weekday::Sat | chrono::Weekday::Sun => println!("It's the weekend"),
        _ => println!("It's a weekday"),
    }

    // A match without an expression is an alternate way to express if/else logic.
    // Also demonstrating how match arms can be non-constants.
    let t = Utc::now();
    match t.hour() {
        0..=11 => println!("It's before noon"),
        _ => println!("It's after noon"),
    }

    // A type match (or comparison) to handle different types.
    let what_am_i = |i: &dyn fmt::Debug| {
        match i.downcast_ref::<bool>() {
            Some(_) => println!("I'm a bool"),
            None => {
                match i.downcast_ref::<i32>() {
                    Some(_) => println!("I'm an int"),
                    None => println!("Don't know type {:?}", i),
                }
            }
        }
    };

    what_am_i(&true);
    what_am_i(&1);
    what_am_i(&"hey");
}

To run the program, ensure you have a main.rs file and use cargo run.

$ cargo run
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type "hey"

In Rust, we use match statements to handle multiple branches. In some cases, we need to use functionality from external crates like chrono for date and time operations. In this example, match statements are used to check both constant values and ranges, demonstrating versatility in conditional statements.

Now, let’s explore more Rust examples to understand the language better.