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
rust-lang.github.io
...This proposal also includes a debug_asset_ne, matching debug_assert_eq.
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 design
This...
RFC 1653
RFC
2016-07-27
~1 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
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
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
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
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
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
rustc-dev-guide.rust-lang.org
...Note that exactly one of the matchers from the various rules should match the invocation; if there is more than one match, the parse is ambiguous, while if there are no matches at all, there is a syntax error.
Assuming exactly one rule matches, macro expansion will then transcribe the...
Guide to Rustc Development
Book
2024-01-01
~16 min read
worldwithouteng.com
...Handling these error variants is straightforward on the calling side thanks to Rust’s pattern matching. Using the match statement, you can easily run different code for different error variants. Further, the compiler ensures that your match statement is exhaustive. If you ever add a new error variant but forget...
Rust Walkthroughs
2023-11-01
~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
matthewkmayer.github.io
...let credentials = DefaultCredentialsProvider::new()
.expect("Couldn't create AWS credentials provider.");
Knowing when to use expect instead of matching against Result or Option is worth understanding. In our sample code, panicking if we can’t get AWS credentials is probably what we want to do. But what about calls to...
News & Blog Posts
2017-06-06
~7 min read
kerkour.com
...They match routes (URLs). For example, the Login page matches the /login route. The Home page matches the / route.
And finally, Services are auxiliary utilities to wrap low-level features or external services such as an HTTP client, Storage...
The goal of our application is simple: It's a portal...
Rust Walkthroughs
2022-06-15
~5 min read
levpaul.com
...For now I’ve just set this command as a build target for when I need it but I’m sure it will eventually annoy me enough to find a better answer.match match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal...
Learn Rust
2020-10-28
~7 min read
codeandbitters.com
...It allows us to apply a closure to convert the matched string into
something else: in the json_bool case, one of the JsonBool variants. You
will probably smell something funny about that code, though: we already matched
the "true" and "false" strings once in the parser generated by the...
News & Blog Posts
2020-07-14
~33 min read
rust-lang.github.io
...Result<!, E>) -> Self {
match x {
Err(e) => Err(From::from(e)),
}
}
}
But Option doesn't need to do anything exciting, so just has a simple implementation, taking advantage of the default parameter:
impl<T> FromResidual for Option<T> {
fn from_residual(x: Self::Residual) -> Self {
match x {
None => None,
}
}
}
In...
RFC 3058
RFC
2020-12-12
~39 min read
willcrichton.net
...These mechanisms can ensure that two variadic argument lists share important properties, like the number of format string holes matches the number of printf arguments.
Part of an ongoing series about type-level programming in Rust. Consider reading part one first! All code in this note can be found in...
News & Blog Posts
2020-06-23
~6 min read