doc.rust-lang.org
...Default,
{
match map.get_mut(&key) {
Some(value) => value,
None => {
map.insert(key.clone(), V::default());
map.get_mut(&key).unwrap()
}
}
}
Because of the lifetime restrictions imposed, &mut map's lifetime overlaps other mutable borrows, resulting in a compile error:
error[E0499]: cannot borrow `*map` as mutable more than once...
The Rustonomicon
Book
2024-01-01
~2 min read
antoinerr.github.io
...match failing_function() {
Ok(s) => println!("{s}"),
Err(e) => match e.downcast_ref() {
Some(MyErrors::LetsFixThisTomorrowError) => (),
Some(MyErrors::ThisDoesntLookGoodError) => (),
Some(MyErrors::ImmaGetFiredError) => (),
None => (),
},
}
Returning early with an error
Finally, anyhow provides a utility macro to return early from your methods with an error: the bail! macro. Here is how it...
Rust Walkthroughs
2023-02-01
~6 min read
arzg.github.io
...Option<ast::Expr>) -> Expr {
if let Some(ast) = ast {
match ast {
// snip
ast::Expr::VariableRef(ast) => Expr::VariableRef {
var: ast.name().unwrap().text().into(),
},
}
} else {
// snip
}
}
// snip
}
That match arm is longer than one line; let’s extract it to a method for consistency:impl Database {
// snip
pub(crate) fn...
Rust Walkthroughs
2021-01-27
~18 min read
ryan-jacobs1.github.io
...fn cleanup() {
let me = smp::me();
let mut cleanup_work = CLEANUP[me].lock();
loop {
match cleanup_work.get_task() {
Some(work) => {work()},
None => {break}
}
}
}
Now we can finish our implementation of surrender and move on to block:
pub fn surrender() {
let mut current_thread: Box<dyn TCB> = match swap_active...
News & Blog Posts
2020-01-14
~9 min read
blog.turbo.fish
...Figuring out what's
inside is a simple manner of matching:
use syn::{Data, DataStruct, Fields};
let fields = match input.data {
Data::Struct(DataStruct { fields: Fields::Named(fields), .. }) => fields.named,
_ => panic!("this derive macro only works on structs with named fields"),
};
Here, we panic!() if the input is not what...
Rust Walkthroughs
2021-02-24
~12 min read
rust-analyzer.github.io
...Your browser does not support the video tag.
#12345 (first contribution) add escapeSequence semantic token type.
#12263 hide type inlay hints for let statements that initialize a closure (enable using rust-analyzer.inlayHints.typeHints.hideClosureInitialization):
#12130 add assist to turn let-else statements into let and match:
Your browser does...
Project/Tooling Updates
2022-05-25
~1 min read
brson.github.io
...Linked error-chain errors are able to propagate backtraces
and have a structural shape that is easy to deeply match, so that e.g.
your error that originated in your utils crate, bubbled through your net
crate, then up through your app crate is easy to pinpoint through pattern
matching...
News & Blog Posts
2016-12-06
~6 min read
rust-lang.github.io
...Since we already allow recursion via const fn and termination of said recursion via if or match, all code enabled by const recursion is already legal now. Some algorithms are better expressed as imperative loops and a lot of Rust code uses loops instead of recursion. Allowing loops in constants...
RFC 2344
RFC
2018-02-18
~2 min read
rust-analyzer.github.io
#3084 better error reporting around workspace loading.
#3102 better error reporting when deserializing wrong config.
#3092 fix error when starting the server immediately after download.
#3100 improved error handling when downloading the server binary.
#3114 fix type inference for match arms of unknown type.
#3121 during auto-import, don’t...
News & Blog Posts
2020-02-18
~1 min read
nikolish.in
...Self::Message) { match message { CounterMessage::Increment => self.count += 1, CounterMessage::Decrement => self.count -= 1, CounterMessage::ChangePage(view) => self.current_view = view }}
We simple update the state of our application by assigning the current_view with the view that is passed by the message.
We now need to somehow produce this...
Observations/Thoughts
2022-06-22
~7 min read
github.com
...Attribute
invocations can only match the `attr` rules, and non-attribute invocations can
only match the non-`attr` rules. This allows adding `attr` rules to an existing
macro without breaking backwards compatibility.
An attribute macro may emit code containing another attribute, including one
provided by an attribute macro. An attribute...
RFC 3697
RFC
2024-09-20
~8 min read
blog.none.at
...If the target returns both the HTML element and the cookie on every single response, the iteration count, HTML match count, and header match count should be identical — any mismatch indicates a parsing or check evaluation bug:=== per-worker results ===
worker iterations html_match header_match ok?
-------------------------------------------------------------------------------------
http://worker1:9091...
Project/Tooling Updates
2026-03-18
~25 min read
doc.rust-lang.org
...In that regard, macro_rules! can work similarly to a match block:
// `test!` will compare `$left` and `$right`
// in different ways depending on how you invoke it:
macro_rules! test {
// Arguments don't need to be separated by a comma.
// Any template can be used!
($left:expr; and $right:expr...
Rust by Example
Book
2024-01-01
~1 min read
speakerdeck.com
Transcript
ALGEBRAIC DATA TYPES
enum Color { Red, Green, Blue }
enum Tree { Empty, Leaf(int), Node(~Tree, ~Tree) }
tag tag int tag ~Tree ~Tree Empty Leaf(int) Node(~Tree, ~Tree)
PATTERN MATCHING
enum Option<T> { None, Some(T) }
fn double(p: ~int) -> int { *p * 2 }
OWNERSHIP
void *realloc(void *, ...); void free...
Discussion + Blog posts
2013-07-29
~1 min read
matklad.github.io
...Repr::Custom(Box::new(Custom { kind, error })),
}
}
pub fn get_ref(
&self,
) -> Option<&(dyn error::Error + Send + Sync + 'static)> {
match &self.repr {
Repr::Os(..) => None,
Repr::Simple(..) => None,
Repr::Custom(c) => Some(&*c.error),
}
}
pub fn into_inner(
self,
) -> Option<Box<dyn error::Error + Send + Sync>> {
match self.repr {
Repr...
Observations/Thoughts
2020-10-21
~8 min read
fredrik.anderzon.se
...Knock, knock", fruits[i]);
println!("WHO'S THERE???");
},
3 => {
println!("{}", fruits[i]);
println!("{}, who?", fruits[i]); },
4 => {
println!("{} you glad I didn't say {}?", fruits[i], fruits[0]);
println!("facepalm");
},
// Rust wants to make sure your match statements always get a match to avoid
// unexpected behaviors, `_` is the "default" or...
News & Blog Posts
2016-05-16
~19 min read
www.freecodecamp.org
...In main let's check that the action passed as an argument is "complete" by using an else if statement:
// in the main function
if action == "add" {
// add action snippet
} else if action == "complete" {
match todo.complete(&item) {
None => println!("'{}' is not present in the list", item),
Some(_) => match todo...
Rust Walkthroughs
2021-01-06
~22 min read
rust-lang.github.io
...The migration lint will be implemented as follows:
• Find method calls matching the name of one of the newly added traits' methods. This can be done either by hardcoding these method names or by setting up some kind of registry through the use of an attribute on the relevant traits...
RFC 3114
RFC
2021-02-16
~6 min read
rust-lang.github.io
...match msg {
// you can reorder too!
Bind { values, formats, .. } => ...
// ...
}
versus
match msg {
Bind(_, _, formats, values, _) => ...
// ...
}
This feature gate was originally put in place because there were many serious bugs in the compiler's support for struct variants. This is not the case today. The issue tracker does not appear have...
RFC 418
RFC
2014-10-25
~2 min read
upsuper.github.io
...matches (Pattern) -> &strfn trim_start_matches (Pattern) -> &strfn trim_end_matches (Pattern) -> &strMatching and findingfn contains (Pattern) -> boolfn starts_with (Pattern) -> boolfn ends_with (Pattern) -> boolfn find (Pattern) -> Option<usize>fn rfind (Pattern) -> Option<usize>fn matches (Pattern) -> Iterator<Item = &str>fn rmatches (Pattern) -> Iterator<Item = &str>fn match_indices...
News & Blog Posts
2019-04-30
~8 min read