Match
Ah, the good ol’ match
statement.
Generally very powerful, one can use it for measly Option
matching:
fn <>(: <>) where : std::fmt:: {
match {
() => !("Got some value: {value:?}"),
=> !("Got no value"),
}
}
Or with more complex match
goodness, like match guards and bindings:
fn (: <>, : ) {
match {
() if > => !("I am really sorry"),
() if == => !("What are the odds?"),
( @ 1.0..10.0) => !("So close!! Only {value} left..."),
(_) => !("Some ways to go..."),
=> !("Debt free!"),
}
}
If Let
Equivalent to checking for a Some
while simultaneously unwrapping the containing value:
fn (: <>) {
if let ( @ ..100.0) = {
!("Debt below three digits!! Only {value} remaining."),
} else {
!("Unable to perform analysis..."),
}
}
This allows you to reduce one level of nesting, as compared to the match
version:
fn (: <>) {
match {
( @ ..100.0) => {
!("Debt below three digits!! Only {value} remaining."),
},
=> {
!("Unable to perform analysis..."),
}
}
}
Note that if you do not need the containing value, use .is_
with an if
expression:
fn (: <>) {
if .() {
!("You have debt."),
} else {
!("You do not have debt."),
}
}
Let Else
The irrefutable version of if let
.
Use this to unwrap a value, changing control flow if the Option
is None
:
fn (: <>, : ) {
let () = else {
!("No debt.");
return;
}
let = / ;
!("You owe {debt}.");
!("You pay {annual_deposit} a year towards your debt.");
!("You will repay your debt after {} years.", );
}
This allows you to reduce one level of nesting after the unwrapping, as compared to the if let
version:
fn (: <>, : ) {
if let () = {
let = / ;
!("You owe {debt}.");
!("You pay {annual_deposit} a year towards your debt.");
!("You will repay your debt after {} years.", );
} else {
!("No debt.");
}
}
Note that if you want to panic!()
or unreachable!()
on None
, use .expect()
or .unwrap()
instead.
fn (: <>, : ) {
let = .("Everyone has debt.");
let = / ;
!("You owe {debt}.");
!("You pay {annual_deposit} a year towards your debt.");
!("You will repay your debt after {} years.", );
}