tonyarcieri.com
...Rust’s pattern matching lets us write match statements that work across all of the variants:
match animal {
Animal::Cat { weight, .. } |
Animal::Dog { weight, .. } |
Animal::Monkey { weight, .. } |
Animal::Fish { weight, .. } |
Animal::Dolphin { weight, .. } |
Animal::Snake { weight, .. } => weight
}
This provides a way to query an attribute across all of the variants...
News & Blog Posts
2016-11-15
~5 min read
www.shuttle.rs
...The advantage of using an enum over just strings is that when we're pattern matching, we can simply match against the different variants instead of having to account for variations in strings.
Enums in Other Languages#
For some context, let's have a look at what enums look like...
Rust Walkthroughs
2023-11-29
~6 min read
doc.rust-lang.org
...RGB(u32, u32, u32),
HSV(u32, u32, u32),
HSL(u32, u32, u32),
CMY(u32, u32, u32),
CMYK(u32, u32, u32, u32),
}
fn main() {
let color = Color::RGB(122, 17, 40);
// TODO ^ Try different variants for `color`
println!("What color is it?");
// An `enum` can be destructured using a `match`.
match...
Rust by Example
Book
2024-01-01
~1 min read
doc.rust-lang.org
...i32) {
// `Option` values can be pattern matched, just like other enums
match checked_division(dividend, divisor) {
None => println!("{} / {} failed!", dividend, divisor),
Some(quotient) => {
println!("{} / {} = {}", dividend, divisor, quotient)
},
}
}
fn main() {
try_division(4, 2);
try_division(1, 0);
// Binding `None` to a variable needs to be type annotated
let none: Option...
Rust by Example
Book
2024-01-01
~1 min read
docs.rust-embedded.org
...Unable to match requested speed 1000 kHz, using 950 kHz
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : clock speed 950 kHz
Info : STLINK v2 JTAG v27 API v2 SWIM v15 VID 0x0483 PID 0x374B
Info : using stlink api v2
Info : Target voltage: 2.919881
Info...
The Embedded Rust Book
Book
2024-01-01
~2 min read
www.abubalay.com
...let mut elements = elements_value(lex, value)?;
loop {
match array_open_elements(elements) {
Either::Left(e) => elements = e,
Either::Right(array) => return Ok(array),
}
}
}
// array = "[" elements * "]"
// elements = elements * "," value
fn array_open_elements(lex: &mut Lex, elements: Elements) ->
Result<Either<Elements, Array>, ParseError>
{
let token = lex.token();
match token {
Token...
News & Blog Posts
2018-04-10
~14 min read
www.propelauth.com
...Json<CreateUrl>,
) -> Response {
// First grab an auth token from a custom header
let token_header = headers.get("X-Auth-Token");
let token = match token_header {
None => return (StatusCode::UNAUTHORIZED, "Unauthorized").into_response(),
Some(header) => header.to_str().unwrap(),
};
// Then verify the token is correct
let verify_result = verify_auth_token...
Rust Walkthroughs
2022-12-14
~7 min read
dwrensha.github.io
...address_book::Reader)
-> ::std::result::Result<(), ::capnp::Error>
{
for person in try!(address_book.get_people()).iter() {
println!("{}: {}", try!(person.get_name()),
try!(person.get_email()));
for phone in try!(person.get_phones()).iter() {
let type_name = match phone.get_type() {
Ok(person::phone_number::Type::Mobile) => "mobile",
Ok(person...
Project Updates
2015-03-23
~1 min read
bitfieldconsulting.com
...let weather = ws.get_weather("New York City,USA").unwrap();
This won’t match what the mock server expects, so naturally enough we
get a failure:
called `Result::unwrap()` on an `Err` value: bad response:
{"message":"Request did not match any route or mock"}
The “bad response” part tells us...
Rust Walkthroughs
2026-05-13
~8 min read
auroranssolis.github.io
...We’ll do this by seeing whether a multiple of two
metavariables needs a leading metavariable in order to match.
macro_rules! luhn {
// Matches:
// - a
// - a b c
// - ...
($head:tt $($tail1:tt $tail2:tt)*) => {
calculate_residue!([$head $($tail1 $tail2)*] [odd] [even] [0])
};
// Matches:
// -
// - a b
// - ...
($($tail1:tt $tail2:tt)*) => {
calculate...
Rust Walkthroughs
2024-02-21
~15 min read
adventures.michaelfbryan.com
...In this case parameters, constants, and function calls all have the highest
possible precedence level.
// src/expr.rs
impl Expression {
fn precedence(&self) -> Precedence {
match self {
Expression::Parameter(_)
| Expression::Constant(_)
| Expression::FunctionCall { .. } => Precedence::Bi,
Expression::Negate(_) => Precedence::Md,
Expression::Binary { op, .. } => op.precedence(),
}
}
}
impl BinaryOperation {
fn precedence(self) -> Precedence {
match...
News & Blog Posts
2020-07-14
~25 min read
adventures.michaelfbryan.com
...In this case parameters, constants, and function calls all have the highest
possible precedence level.
// src/expr.rs
impl Expression {
fn precedence(&self) -> Precedence {
match self {
Expression::Parameter(_)
| Expression::Constant(_)
| Expression::FunctionCall { .. } => Precedence::Bi,
Expression::Negate(_) => Precedence::Md,
Expression::Binary { op, .. } => op.precedence(),
}
}
}
impl BinaryOperation {
fn precedence(self) -> Precedence {
match...
News & Blog Posts
2020-07-21
~25 min read
recursion.wtf
...let layer = match seed {
ExprBoxed::Add { a, b } => ExprLayer::Add { a, b },
ExprBoxed::Sub { a, b } => ExprLayer::Sub { a, b },
ExprBoxed::Mul { a, b } => ExprLayer::Mul { a, b },
ExprBoxed::LiteralInt { literal } => ExprLayer::LiteralInt { literal: *literal },
};
This matches on seed, a value of type &ExprBoxed, and consumes it to create layer...
Rust Walkthroughs
2022-07-20
~13 min read
kerkour.com
...Then we can handle a potential error with match.
fn question() -> Result<(), Error> {
let x = // ...
match ultimate_answer(x) {
Ok(_) => // do something
Err(Error::More) => // do something
Err(Error::Less) => // do something
Err(Error::WrongAnswer) => // do something
}
// ...
}
Or, the most common way to handle errors, forward them with ?.
fn question...
Observations/Thoughts
2022-02-09
~4 min read
sireliah.com
...6 nodes.sort_by(|a, b| b.prob.partial_cmp(&a.prob;).unwrap()); 7 8 let first = match nodes.pop() { 9 Some(i) => i,10 None => return,11 };12 13 let second: Node = match nodes.pop() { 14 Some(i) => i,15 None => return,16 };17 18 /// Create new node and...
News & Blog Posts
2017-06-27
~8 min read
www.bekk.christmas
...Then we pattern match on the vector as a slice – a view into an array.When the compiler sees a match expression, it matches the value with the list of patterns and stops when encountering the first pattern that matches. Each branch has the form of SomePattern => some_expression(),. For...
Rust Walkthroughs
2022-12-07
~17 min read
bertptrs.nl
...my_print!(match) would not be accepted.
Edition 2024 brings the :tt fragment specifier up-to-date with the new additions to the language,
allowing it to match _- and const expressions as part of an :expr fragment. If you must
maintain the previous behaviour, you can replace :expr with :expr...
Observations/Thoughts
2025-02-26
~17 min read
blog.logrocket.com
...Declarative macros provide a match like an interface where on match the macro is replaced with code inside the matched arm.
Creating declarative macros
// use macro_rules! <name of macro>{<Body>}
macro_rules! add{
// macth like arm for macro
($a:expr,$b:expr)=>{
// macro expand to this code
{
// $a and...
Rust Walkthroughs
2021-02-03
~17 min read
www.sea-ql.org
...513] Added the MATCH, -> and ->> operators for SQLite
use sea_query::extension::sqlite::SqliteBinOper;assert_eq!( Query::select() .column(Char::Character) .from(Char::Table) .and_where(Expr::col(Char::Character).binary(SqliteBinOper::Match, Expr::val("test"))) .build(SqliteQueryBuilder), ( r#"SELECT "character" FROM "character" WHERE "character" MATCH ?"#.to_owned(), Values(vec...
Project/Tooling Updates
2023-01-04
~3 min read
iev.ee
...i also added a \p{utf8} class that lets you constrain matches to valid UTF-8. rust's regex crate guarantees that matches only occur on valid UTF-8 boundaries, so how do you do that when your engine operates on raw bytes? you intersect (&) with the language of valid...
Observations/Thoughts
2026-03-11
~12 min read