blog.burntsushi.net
...option-ex-string-findfn main_find() {
let file_name = "foobar.rs";
match find(file_name, '.') {
None => println!("No file extension found."),
Some(i) => println!("File extension: {}", &file_name[i+1..]),
}
}
This code uses pattern
matching to do case
analysis on the Option<usize> returned by the find function. In fact...
Notable Links
2015-05-18
~57 min read
wapl.es
...This needs to
be wrapped in a match to be usable by sort_unstable_by in Triangle::sorted_clockwise:
points.sort_unstable_by(|a, b| {
let order = sort_clockwise(*a, *b, center);
match order {
true => Ordering::Greater,
false => Ordering::Less
}
});
Changing to use Ordering
The above code doesn't feel...
Miscellaneous
2020-07-28
~11 min read
getcode.substack.com
...Let's try evaluating them by writing an interpreter.impl Expr {
fn eval(&self) -> i32 {
match self {
Expr::Lit(i) => *i,
Expr::Neg(r) => -r.eval(),
Expr::Add(r1, r2) => r1.eval() + r2.eval(),
}
}
}Easy enough - we pattern match on Expr and recursively call eval. Calling eval on the example...
Rust Walkthroughs
2023-03-29
~25 min read
immunant.com
...We added some extra sanity checking for global arrays and found real-world examples where the size of an array declaration didn’t match its definition. Aside from that case, it seems that in practice most global declaration types match their definitions. Functions are another matter entirely. We match extern...
News & Blog Posts
2019-12-24
~15 min read
xion.io
...let result = results.into_iter().fold(Ok(vec![]), |mut v, r| match r {
Ok(x) => { v.as_mut().map(|v| v.push(x)); v },
Err(e) => Err(e),
});
and in a loop form:
let mut result = Ok(vec![]);
for r in results {
match r {
Ok(x) => result.as_mut().map...
News & Blog Posts
2017-04-11
~5 min read
doc.rust-lang.org
Unpacking options with ?
You can unpack Options by using match statements, but it's often easier to use the ? operator. If x is an Option, then evaluating x? will return the underlying value if x is Some, otherwise it will terminate whatever function is being executed and return None.
fn...
Rust by Example
Book
2024-01-01
~1 min read
dygalo.dev
...Now we can handle the rules and compile CSS selectors for further matching against them:
use kuchiki::Selectors;
fn process_css(document: &NodeRef, css: &str) -> Result<(), InlineError> {
// ...
for rule in rules {
let (selector, block) = rule?;
if let Ok(matching_elements) = document.select(selector) {
for el in matching_elements {
todo!()
}
}
}
Ok...
Learn Standard Rust
2020-08-11
~18 min read
blog.logrocket.com
...However, a matches the word, which matches words (“at least one word“). So, our string that contains invalid word separators still successfully matches the words rule because words is only matching part of the input.
We can rectify this by changing our rule to parse until the end of the...
News & Blog Posts
2020-06-23
~20 min read
developers.facebook.com
...Then, the app utilizes Rust’s pattern matching feature using the match keyword. To test things out, I add the “tw” as one of my commands to redirect to Twitter. If there are no matches, it simply redirects to Google. Notice, I am not yet using the query string arguments...
News & Blog Posts
2020-06-30
~21 min read
geeklaunch.net
...expr) => {
println!("{} {}", $a, $b);
};
}Declarative macros accept Rust tokens as input and perform pattern matching against them. In the example above, the macro my_macro matches two different patterns:An identifier and an expression separated by a fat arrow =>, andAn identifier and an expression separated by a comma ,.This macro...
Rust Walkthroughs
2022-11-02
~8 min read
blog.adamchalmers.com
...We can use separated_list1 to match a line, then match and discard a newline, then match a line, then match and discard a newline, etc etc until the end of the file.
use nom::character::complete::line_ending;
/// Parse the whole Advent of Code day 5 text file.
pub...
Rust Walkthroughs
2022-01-12
~16 min read
github.com
...These two variants correspond
to concrete types for when the key matched something in the map, and when the key didn't, respectively.
If there isn't a match, the user has exactly one option: insert a value using `set`, which will also insert
the guarantor, and destroy the Entry...
RFC 216
RFC
2014-08-28
~7 min read
contextgeneric.dev
...While IsNothing is used for absent fields in partial records, we use IsVoid to represent removed or matched variants in partial variants. This ensures that once a variant has been extracted, it cannot be matched again — preserving both soundness and safety in CGP’s type-driven pattern matching.
Once an...
Rust Walkthroughs
2025-07-30
~58 min read
pramode.in
...We can use pattern
matching to match for the event and to extract the values associated with the
event. In the above case, we pattern match for a KeyDown and when we get such an
event, we extract the actual key code, if the key is an Esc key, we...
Blog Posts
2016-10-18
~9 min read
epage.github.io
...let cmd = Command::new("mycmd")
.arg(
Arg::new("quiet")
.long("quiet")
.action(clap::builder::ArgAction::SetTrue)
)
.arg(
Arg::new("verbose")
.long("verbose")
.action(clap::builder::ArgAction::Count)
);
let matches = cmd.try_get_matches_from(
["mycmd", "--quiet", "--quiet", "--verbose", "--verbose", "--verbose"]
).unwrap();
assert_eq!(
*matches.get_one::<bool>("quiet").expect("defaulted...
Project/Tooling Updates
2022-06-15
~5 min read
kbknapp.github.io
...Called on top level parent app ONLY then recursively calls
the real parsing function for all subcommands
let matches = App::new("myprog")
.get_matches();
fn get_matches_from<I, T>(self, itr: I) -> ArgMatches<'ar, 'ar> where I: IntoIterator<Item=T>, T: AsRef<str>[−]
Starts the parsing process. Called on...
New Crates & Project Updates
2016-07-05
~10 min read
domain-j.com
...pub fn parse_frontmatter(file_content: &str) -> (HashMap<String, gray_matter::Pod>, String) {
let matter = Matter::<gray_matter::engine::YAML>::new();
let result = matter.parse(file_content);
let frontmatter = match result.data {
Some(data) => match data {
gray_matter::Pod::Hash(map) => map,
_ => panic!("Expected Pod::Hash but found other variant...
Observations/Thoughts
2024-06-26
~10 min read
robert.kra.hn
...Edit server/src/main.rs to match:use axum::{response::IntoResponse, routing::get, Router};
use clap::Parser;
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
use std::str::FromStr;
// Setup the command line interface with clap.
#[derive(Parser, Debug)]
#[clap(name = "server", about = "A server for our wasm project!")]
struct Opt {
/// set...
Rust Walkthroughs
2022-04-06
~12 min read
rust.code-maven.com
...Then we need a pattern matching using match. We need one arm for each one of the subcommands. Because we made the subcommand itself
optional, we'll need a default arm to handle the None case.
fn main() {
let args = Cli::parse();
println!("root: {:?}", args.root);
match &args.command {
Some...
Miscellaneous
2024-01-17
~3 min read
www.matildasmeds.com
...We can add player_id and match_id as fields on the Span, like so: 1struct TicTacToe {}
2
3impl TicTacToe {
4 #[tracing::instrument(name = "TicTacToe::process_turn", skip_all, fields(match_id = %match_id, player_id = %player_id))]
5 pub async fn process_turn(&self, match_id: &MatchId, player_id...
Observations/Thoughts
2024-04-17
~8 min read