Title here
Summary here
Our example demonstrates several ways to use switch
statements in Rust. Here’s the full translated code.
use std::time::{SystemTime, UNIX_EPOCH};
use std::fmt::{self, Display, Debug}; // Including format traits
fn main() {
// Here's a basic switch equivalent using match.
let i = 2;
println!("Write {} as {}", i, match i {
1 => "one",
2 => "two",
3 => "three",
_ => "unknown",
});
// Using a match statement to handle multiple cases
let weekday = {
let duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let secs = duration.as_secs();
let days = (secs / 86400) % 7;
match days {
0 => "Sunday",
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6 => "Saturday",
_ => "Unknown",
}
};
match weekday {
"Saturday" | "Sunday" => println!("It's the weekend"),
_ => println!("It's a weekday"),
};
// Match without an expression is not a direct feature in Rust, but using if/else chains can simulate this.
let now = {
let duration = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let secs = duration.as_secs();
let hours = (secs / 3600) % 24;
hours
};
if now < 12 {
println!("It's before noon");
} else {
println!("It's after noon");
}
// Type switch equivalent using Rust Enums and traits.
enum Type {
Bool(bool),
Int(i32),
String(String),
}
impl Display for Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Type::Bool(b) => write!(f, "I'm a bool"),
Type::Int(i) => write!(f, "I'm an int"),
Type::String(_) => write!(f, "Don't know type string"),
}
}
}
let what_am_i = |i: Type| {
println!("{}", i);
};
what_am_i(Type::Bool(true));
what_am_i(Type::Int(1));
what_am_i(Type::String(String::from("hey")));
}
Let’s break down the various parts of the code.
match
statement is used to handle different cases. This is similar to the switch
statement in other programming languages.match
statement to match multiple patterns using the |
operator.if/else
statements in Rust can serve the purpose, as shown in the time-based example.To run the example, save the code in a file named switch.rs
and use the Rust compiler to execute it.
$ rustc switch.rs
$ ./switch
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string
This demonstrates the various ways you can use match statements in Rust to handle different scenarios, similar to how you might use switch statements in other languages.