Member-only story
Effective Rust item3 Avoid Direct Matching Options and Results
Item 1
illustrates the benefits of enumerations and shows how to force programmers to consider all possibilities with a match expression; this project will further explore situations where match expressions should be avoided (at least explicitly).
Item 1
also introduces two commonly applicable enumeration types provided by the Rust standard library:
Option < T >
: used to express a value (type T) may or may not exist;Result < T, E >
: Used when an operation may not successfully return a value (of type T), but instead return an error (of type E).
For these tospecific enumeration types, explicit use of match expressions often results in code that is more verbose than necessary and does not conform to Rust idioms.
The first situation where a match expression is not necessary is when only the value itself is concerned and missing values (and their related errors) are ignored. In this case, a match expression is not necessary.
struct S {
field: Option<i32>,
} let s = S { field: Some(42) };
match &s.field {
Some(i) => println!("field is {}", i),
None => {}
}
In this case, using an if let
expression not only reduces the number of lines of code, but more importantly, it is clearer:
if let Some(i) = &s.field {
println!("field is {}", i);
}