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
docs.rs
...use number_prefix::NumberPrefix; let amount = 8542_f32; let result = match NumberPrefix::decimal(amount) { NumberPrefix::Standalone(bytes) => { format!("The file is {} bytes in size", bytes) } NumberPrefix::Prefixed(prefix, n) => { format!("The file is {:.1} {}B in size", n, prefix) } }; assert_eq!("The file is 8.5 kB in size", result...
Crate
v0.4.0
2020-04-07
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
crates.io
...To be compatible, Zebra had to implement a special library, ed25519-zebra , to provide Zcash-flavored Ed25519, attempting to match libsodium 1.0.15 exactly. And the initial attempt to implement ed25519-zebra was also incompatible, because it precisely matched the wrong compile-time configuration of libsodium. This problem is...
Crate
v2.1.0
2023-01-23
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
rodarmor.com
...for c in text.chars() {
match state {
…
State::Backslash => {
match c {
'n' => cooked.push('\n'),
…
}
…
}
…
}
}
So just asks rustc to insert the result of evaluating the Rust '\n'
character escape. Let's take a look at how rustc handles '\n'.
rustc's escape code handling is in the lexer, in...
Observations/Thoughts
2024-10-02
~2 min read
github.com
...This proposal also includes a `debug_asset_ne`, matching `debug_assert_eq`.
## Motivation
[motivation]: #motivation
This feature, among other reasons, makes testing more readable and consistent as
it complements `asset_eq`. It gives the same style panic message as `assert_eq`,
which eliminates the need to write it yourself.
## Detailed...
RFC 1653
RFC
2016-07-27
~1 min read
loige.co
...select a part, then print it on the standard output.Another interesting example in our code base involved the match expression. This was the code before the refactoring:impl fmt::Display for JWTParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { JWTParseError::MissingSection() => write!(f, "{}", "Missing token...
Observations/Thoughts
2020-10-14
~16 min read