rapha.land
...Add a new variant later and every match site that doesn’t cover it stops compiling, with the type checker pointing at the exact line. That is the safety property pattern matching is for.
Match also works as an expression:
const name: []u8 = match (color) {
Color.Red { "red" }
Color.Green...
Project/Tooling Updates
2026-07-08
~26 min read
amanjeev.com
...non-exhaustive patterns: `&_` not covered
--> src/main.rs:12:11
|
12 | match place {
| ^^^^^ pattern `&_` not covered
|
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
= note: the matched value is of type `&str`I do not enjoy writing tests and eating my...
Observations/Thoughts
2020-09-16
~13 min read
ricardoanderegg.com
...usize = if ctx.len() <= arg_cap_group {
// no capture group, use default
0
} else {
ctx.get(arg_cap_group).context("capture group")?
};
// let mut caploc = re.capture_locations();
// re.captures_read(&mut caploc, input_value);
if let Some(cap) = re.captures(input_value) {
match cap.get(cap_group) {
None => empty...
Rust Walkthroughs
2022-05-18
~10 min read
www.halcyon.hr
...There are several different ways to do this - and it all depends on what you want to do.Pattern matching errorsA simple way of figuring out what’s going on is to use pattern matching on the result type.match how_many_bananas(0) {
Ok(number) => println!("You have {} bananas...
News & Blog Posts
2020-06-16
~13 min read
www.hoverbear.org
...num_read])
.unwrap();
if let Ok(rpc) = json::decode::<RemoteProcedureCall<T>>(data) {
match rpc {
RemoteProcedureCall::RequestVote(call) =>
self.handle_request_vote(call, source),
RemoteProcedureCall::AppendEntries(call) =>
self.handle_append_entries(call, source),
}
} else if let Ok(rpr) = json::decode::<RemoteProcedureResponse>(data) {
match rpr {
RemoteProcedureResponse::Accepted { .. } =>
self.handle_accepted(rpr, source...
Blog Posts
2015-02-09
~5 min read
doc.rust-lang.org
...Result<i32, ParseIntError>) {
match result {
Ok(n) => println!("n is {}", n),
Err(e) => println!("Error: {}", e),
}
}
fn main() {
print(multiply("10", "2"));
print(multiply("t", "2"));
}
The try! macro
Before there was ?, the same functionality was achieved with the try! macro. The ? operator is now recommended, but you may still...
Rust by Example
Book
2024-01-01
~1 min read
relm4.org
...1
2
3
4
5
6
7
8
9
10
11
let component = MyComponent::builder()
// Start the component service with an initial parameter
.launch("Hello world")
// Attach the returned receiver's messages to this closure.
.connect_receiver(move |sender, message| match message {
// Transform and forward the message
Output::HelloThere => {
sender...
Project/Tooling Updates
2022-07-27
~5 min read
iev.ee
nginx/1.28.0
Observations/Thoughts
2026-03-18
~1 min read
dev.to
...Uuid) -> ApiResponse {
let mut v = userdb.db.lock().unwrap();
let users = &mut *v;
let pos = users.iter().position(|x| x.id.to_string() == id.to_string());
match pos {
Some(p) => {
if v[p].match_password(&user.password) {
match &user.new_password {
Some(passw) => {
v[p].update_password(&passw);
ApiResponse::ok...
Rust Walkthroughs
2020-11-18
~18 min read
ruudvanasseldonk.com
...The implementation is a big match statement. For example, this is the check for an if-else expression:let expr_type = match expr {
Expr::IfThenElse {
condition_span,
condition,
body_then,
body_else,
span_then,
span_else,
..
} => {
self.check_expr(type_bool_condition(), *condition_span, condition)?;
let type_then = self.check...
Observations/Thoughts
2024-07-24
~15 min read
asquera.de
...let res = match req {
ExampleRequest::Get { url: url } => {
match db.get(&url) {
Some(v) => ExampleResponse::Ok { content: v.clone() },
None => ExampleResponse::NotFound,
}
},
ExampleRequest::Post { url: url, content: content } => {
match db.insert(url, content) {
Some(v) => ExampleResponse::Ok { content: v },
None => ExampleResponse::Ok { content: "".into() },
}
}
};
println!("Database: {:?}", *db);
// Return the result...
News & Blog Posts
2017-03-07
~26 min read
rustc-dev-guide.rust-lang.org
...Most error annotations need to match with the line of the diagnostic. There are several ways to match the message with the line (see the examples below):
• ~: Associates the error level and message with the current line
• ~^: Associates the error level and message with the previous error annotation line. Each...
Guide to Rustc Development
Book
2024-01-01
~19 min read
github.com
...We will also query the oauth_github table to see if the crates.io username and GitHub username match. If they do match, we will continue with adding this user as an owner. If they don't match, we will return an error containing information about the mismatch and asking...
RFC 3946
RFC
2026-04-07
~28 min read
matthewkmayer.github.io
...pub fn generate_source(service: &Service, writer: &mut FileWriter) -> IoResult {
match service.protocol() {
"json" => generate(writer, service, JsonGenerator, JsonErrorTypes),
"query" | "ec2" => generate(writer, service, QueryGenerator, XmlErrorTypes),
"rest-json" => generate(writer, service, RestJsonGenerator, JsonErrorTypes),
"rest-xml" => generate(writer, service, RestXmlGenerator, XmlErrorTypes),
protocol => panic!("Unknown protocol {}", protocol),
}
}
The function signature shows it...
News & Blog Posts
2017-06-27
~8 min read
calculist.org
...function search(corpus, search) {
var ls = lines(corpus);
var total = 0;
for (var i = 0, n = ls.length; i < n; i++) {
total += wcLine(ls[i], search);
}
return total;
}
Searching an individual line involves splitting the line up into word and matching each word against the search string:
function wcLine(line...
News & Blog Posts
2015-12-28
~6 min read
developerlife.com
...This combinator takes a range of characters (2, 2) and applies the
function match_is_hex_digit to determine whether the char is a hex digit (using
is_ascii_hexdigit() on the char). This is used to match a valid hex digit. It returns a
&str slice of the matched...
Rust Walkthroughs
2023-05-24
~20 min read
github.com
...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:
```rust
impl<T> FromResidual for Option<T> {
fn from_residual(x: Self::Residual) -> Self {
match x {
None => None...
RFC 3058
RFC
2020-12-12
~44 min read
hacks.mozilla.org
...This function is essentially just a large match statement over the opcode of the root CLIF instruction, with the match-arms looking deeper as needed.
Here is a simplified version of the match-arm for an integer add operation lowered to AArch64 (the full version is here):
<span class="k...
Observations/Thoughts
2020-10-14
~17 min read
siciarz.net
...use std::env;
fn main() {
match env::var("LANG") {
Ok(lang) => println!("Language code: {}", lang),
Err(e) => println!("Couldn't read LANG ({})", e),
};
}
$ cargo run
Language code: pl_PL.UTF-8
envy
envy is a small crate that uses serde
to automatically deserialize process environment into a Rust struct.
#![feature...
News & Blog Posts
2016-12-06
~3 min read
www.seventeencups.net
...i32) -> f32 {
match index {
0 => self.threshold,
_ => 0.0,
}
}
fn set_parameter(&mut self, index: i32, value: f32) {
match index {
// We don't want to divide by zero, so we'll clamp the value
0 => self.threshold = value.max(0.01),
_ => (),
}
}
fn get_parameter_name(&self, index: i32) -> String {
match...
News & Blog Posts
2017-03-28
~6 min read