santiagopastorino.com
...usize) -> &mut String {
match map.get_mut(&key) {
Some(value) => value,
None => {
map.insert(key, "".to_string());
map.get_mut(&key).unwrap()
}
}
}
fn main() {
let map = &mut HashMap::new();
map.insert(22, format!("Hello, world"));
map.insert(44, format!("Goodbye, world"));
assert_eq!(&*get_default(map, 22), "Hello, world");
assert...
News & Blog Posts
2018-01-09
~5 min read
doc.rust-lang.org
...let mut into_iter = vec2.into_iter();
// `iter()` yields `&i32`, and `find` passes `&Item` to the predicate.
// Since `Item = &i32`, the closure argument has type `&&i32`,
// which we pattern-match to dereference down to `i32`.
println!("Find 2 in vec1: {:?}", iter.find(|&&x| x == 2));
// `into_iter()` yields `i32`, and...
Rust by Example
Book
2024-01-01
~1 min read
doc.rust-lang.org
while let
Similar to if let, while let can make awkward match sequences more tolerable. Consider the following sequence that increments i:
// Make `optional` of type `Option<i32>`
let mut optional = Some(0);
// Repeatedly try this test.
loop {
match optional {
// If `optional` destructures, evaluate the block.
Some(i) => {
if i...
Rust by Example
Book
2024-01-01
~1 min read
doc.rust-lang.org
...use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn main() {
// Create a path to the desired file
let path = Path::new("hello.txt");
let display = path.display();
// Open the path in read-only mode, returns `io::Result<File>`
let mut file = match File::open(&path) {
Err...
Rust by Example
Book
2024-01-01
~1 min read
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
xd009642.github.io
...use std::{
backtrace::{Backtrace, BacktraceStatus},
io::{self, Write},
panic::{self, PanicHookInfo},
thread,
};
fn default_like_hook(info: &PanicHookInfo<'_>) {
let thread = thread::current();
let name = thread.name().unwrap_or("<unnamed>");
let message = match info.payload().downcast_ref::<&str>() {
Some(message) => *message,
None => match info.payload().downcast_ref::<String>() {
Some(message) => message...
Observations/Thoughts
2026-11-11
~4 min read
doc.rust-lang.org
...fn main() {
// Try changing the values in the array, or make it a slice!
let array = [1, -2, 6];
match array {
// Binds the second and the third elements to the respective variables
[0, second, third] =>
println!("array[0] = 0, array[1] = {}, array[2] = {}", second, third),
// Single values can be ignored...
Rust by Example
Book
2024-01-01
~1 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
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
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
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
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
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
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
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
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
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