blog.codecentric.de
...While this does not completely match up with all the capabilities of the “init-check-update for loop”, it does very elegantly cover the most common use. More complex cases will need to be written out using while.
Match
1fn match_it(x: Option<i32>, flag: bool) -> i32 {
2 match...
Learn Standard Rust
2020-09-16
~37 min read
dev.to
...The parser splits up spaces per word, and provides them in order within the Vec. (Matched quotes are interpreted as a single word in our situation).
main()
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = ApplicationArguments::from_args();
match args.subcommand {
SubCommand::StartServer(opts) => {
println!("Start the server...
Learn More Rust
2020-08-26
~11 min read
doc.rust-lang.org
...Because there may not be any matching element, select_first returns an Option<ElementRef>. Finally, we use the Option::map method, which lets us work with the item in the Option if it’s present, and do nothing if it isn’t. (We could also use a match expression here...
The Rust Programming Language
Book
2024-02-01
~14 min read
kobzol.github.io
...HashSet<(ObjectName, Ident)>,
}
impl Visitor for CheckNotNullWithoutDefault {
type Break = ();
fn pre_visit_statement(&mut self, statement: &Statement) -> ControlFlow<Self::Break> {
if let Statement::AlterTable {
operations, name, ..
} = statement
{
for op in operations {
match op {
AlterTableOperation::AddColumn { column_def, .. } => {
let has_not_null = column_def
.options
.iter()
.any(|option| option.option == ColumnOption...
Observations/Thoughts
2025-03-26
~6 min read
kerkour.com
...Q, user: &User) -> Result<(), Error> {
const QUERY: &str = "INSERT INTO users (id, email)
VALUES ($1, $2)";
sqlx::query(QUERY)
.bind(user.id)
.bind(&user.email)
.execute(db)
.await
.map_err(|err| match err {
sqlx::Error::Database(db_err) if db_err.constraint().is_some() => Error::EmailAlreadyInUse,
err => Error::Unspecified(format...
Rust Walkthroughs
2025-04-02
~6 min read
forgestream.idverse.com
...true,
})
} else {
None
}
}
fn main() {
let user_id = 12;
match find_user_by_id(user_id) {
Some(user) => match user.get_greetings() {
Ok(message) => println!("{}", message),
Err(err) => println!("Error: {}", err),
},
None => println!("User not found."),
}
}
What is happening is that:
The script will find a user by the id...
Observations/Thoughts
2025-08-06
~4 min read
coaxion.net
...gio::File) -> Result<(), String> { // Try to open the file let (_file, strm) = await!(file.read_async_future(glib::PRIORITY_DEFAULT)) .map_err(|(_file, err)| format!("Failed to open file: {}", err))?; Ok(())}fn main() { [...] let future = async_block! { match await!(read_file(file)) { Ok(()) => (), Err(err) => eprintln!("Got error: {}", err), } l...
News & Blog Posts
2018-04-24
~13 min read
rust-lang.github.io
...The innermost expression that encloses both of these expressions is the match itself (as depicted above), and hence the borrow is considered to extend until the end of the match. Unfortunately, the match encloses not only the Some branch, but also the None branch, and hence when we go to...
RFC 2094
RFC
2017-08-02
~66 min read
blog.merigoux.fr
...If the output of one test case matches, we can be a little bit more confident that our program is correct. But how can we be sure it will work in all situations? What if our test cases missed a corner case in our algorithm?
One way to increase confidence...
News & Blog Posts
2019-04-16
~9 min read
siciarz.net
...uint, primes: &Primes) -> Option<uint> {
use std::iter::MultiplicativeIterator;
match primes.factor(n) {
Ok(factors) => Some(factors.into_iter().map(|(_, x)| x + 1).product()),
Err(_) => None,
}
}
The trick is to multiply all prime factor exponents, incremented before multiplication. See the explanation at Maths Challenge for the curious. So when we...
Blog Posts
2014-12-08
~3 min read
www.shuttle.rs
...The match keyword allows us to match the current event against a set of patterns. If the pattern matches, we execute the code in the corresponding branch.
If the Result is Ok, we match against the XmlEvent::StartElement variant. This variant indicates that we are inside an opening tag.
In...
Observations/Thoughts
2023-06-21
~9 min read
mender.io
...Through utilizing the pattern matching capabilities of Rust, the initial state-machine skeleton looks like:
loop {
let (state, action) = match (cur_state, cur_action) {
(ExternalState::Init, Event::Uninitialized) => {
match InitState::is_committed() {
true => (ExternalState::Idle, Event::None),
false => (ExternalState::Idle, Event::None),
}
}
(ExternalState::Idle, _) if !client.is_authorized => {
debug!("Client...
Learn More Rust
2020-08-18
~11 min read
kmcallister.github.io
...main() {
::std::io::stdio::println_args(
::std::fmt::Arguments::new({
#[inline]
#[allow(dead_code)]
static __STATIC_FMTSTR: &'static [&'static str]
= &["Hello, world!"];
__STATIC_FMTSTR
}, &match () { () => [], }));
}
Freeze the shape of the tree
Assign each node a unique NodeId
Build an index by NodeId of AST nodes and their parents
See libsyntax...
Blog Posts
2015-01-19
~6 min read
blog.digital-horror.com
...Think of this as a simple client-server connection.loop {
match socket.read(&mut buf).await {
Ok(0) => returing,
Ok(n) => {
println!(
"received {} bytes, msg: {}",
n,
String::from_utf8_lossy(buf.clone()[..n].to_vec().as_slice())
);
socket
.write_all(&buf[..n])
.await
.expect("failed to write data to socket...
Observations/Thoughts
2024-05-29
~6 min read
gill.net.in
...u16,
) -> Option<(Device<T>, DeviceHandle<T>)> {
let devices = match context.devices() {
Ok(d) => d,
Err(_) => return None,
};
for device in devices.iter() {
let device_desc = match device.device_descriptor() {
Ok(d) => d,
Err(_) => continue,
};
if device_desc.vendor_id() == vid && device_desc.product_id() == pid {
match device.open() {
Ok(handle...
Learn More Rust
2020-08-04
~14 min read
rust-lang-nursery.github.io
...guess_format reads the leading magic bytes and returns the matching ImageFormat, which in turn gives the MIME type through ImageFormat::to_mime_type. Only the header is examined, so a short prefix of the file is enough.
Inspect image EXIF metadata
[![kamadak-exif-badge]][kamadak-exif] [![cat-multimedia-badge...
The Rust Cookbook
Book
2024-01-01
~1 min read
doc.rust-lang.org
...is a slice to the original string, hence no new
// allocation is performed
let chars_to_trim: &[char] = &[' ', ','];
let trimmed_str: &str = string.trim_matches(chars_to_trim);
println!("Used characters: {}", trimmed_str);
// Heap allocate a string
let alice = String::from("I like dogs");
// Allocate new memory and store the...
Rust by Example
Book
2024-01-01
~4 min read
whileydave.com
...usize = __nondet();
// Apply Constraints
__VERIFIER_assume(len <= LIMIT);
__VERIFIER_assume(i < len);
__VERIFIER_assume(xs[i] == x);
// Compute result
let result = index_of(&xs[..len],x);
// Check it matches
assert!(xs[result] == x);
}
This is roughly similar to before, except we now require some i
where xs[i] == x. Also...
Observations/Thoughts
2021-10-27
~6 min read
www.shuttle.rs
...We want to check the row with that username has a password that matches. If the credentials match then we create a new session:
Then we refer back to the signup section and replicate the same HTML form and handler that renders the Tera template as seen before but for...
Observations/Thoughts
2022-08-31
~12 min read
rustc-dev-guide.rust-lang.org
...Destruction scopes are also made explicit.
•
Statements, expressions, match arms, blocks, and parameters are stored separately. For example, statements in the stmts array reference expressions by their index (represented as a ExprId) in the exprs array.
The THIR lives in rustc_mir_build::thir. To construct a thir::Expr, you...
Guide to Rustc Development
Book
2024-01-01
~4 min read