solang.readthedocs.io
...function get() public view returns (bool) { return value; } } "#, 0).unwrap(); for part in &tree.0 { match part { SourceUnitPart::ContractDefinition(def) => { println!("found contract {:?}", def.name); for part in &def.parts { match part { ContractPart::VariableDefinition(def) => { println!("variable {:?}", def.name); } ContractPart::FunctionDefinition(def) => { println!("function {:?}", def.name); } _ => (), } } } _ => (), } }
Crate
v0.3.5
2025-06-22
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
docs.rs
...Parsing use svg::node::element::path::{Command, Data}; use svg::node::element::tag::Path; use svg::parser::Event; let path = "image.svg"; let mut content = String::new(); for event in svg::open(path, &mut content).unwrap() { match event { Event::Tag(Path, _, attributes) => { let data = attributes.get("d").unwrap(); let data...
Crate
v0.18.0
2024-09-27
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
crates.io
Glob-matched recursive file system walking. GlobWalk Recursively find files in a directory using globs. This crate is now in a perpetual maintnance mode and new users should probably cosider using glob . Comparison to the glob crate This crate was origially written years ago, when glob was a very differet...
Crate
v0.9.1
2024-01-06
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
docs.rs
A fast library for efficiently matching ignore files such as `.gitignore`
against file paths.
ignore The ignore crate provides a fast recursive directory iterator that respects various filters such as globs, file types and .gitignore files. This crate also provides lower level direct access to gitignore and file type matchers...
Crate
v0.4.33
2026-08-04
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
docs.rs
...server.expect( Expectation::matching(request::method_path("GET", "/foo")).respond_with(status_code(200)), ); // Configure the server to also receive between 1 and 3 POST /bar requests // with a json body matching {'foo': 'bar'}, and respond with a json body // {'result': 'success'} server.expect( Expectation::matching(all_of![ request::method...
Crate
v0.16.4
2026-01-06
crates.io
...use jiff::{ToSpan, Zoned}; use parse_datetime::{parse_datetime_at_date, ParsedDateTime}; let now = Zoned::now(); let after = parse_datetime_at_date(now.clone(), "+3 days"); match after.unwrap() { ParsedDateTime::InRange(z) => assert_eq!(now.checked_add(3.days()).unwrap(), z), ParsedDateTime::Extended(_) => unreachable!("unexpected for this input"), } For DateTime...
Crate
v0.15.0
2026-07-05
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