mirror of
https://github.com/darkicewolf50/RustBrock.git
synced 2025-07-06 11:07:12 -06:00
finished ch6
This commit is contained in:
@ -916,4 +916,36 @@ if you want nothing to happen from the ignore all then return a unit type from t
|
||||
|
||||
for example the arm _ => () does this, this should not be used in the case of a match trying to return something
|
||||
|
||||
# If Let
|
||||
# Concise Flow Control with if let
|
||||
|
||||
This is a concise way of handling the case where there is only 1 arm and the rest are ignored using _
|
||||
|
||||
this would look like
|
||||
```rust
|
||||
let config_max = Some(3u8); // Option<u8> is the value owned by the variable
|
||||
match config_max {
|
||||
Some(max) => println!("The maximum is configured to be {max}"),
|
||||
_ => (), // annoying boilerplate
|
||||
}
|
||||
```
|
||||
|
||||
here is how to remove the boilerplate with a if let
|
||||
this behaves just like the match above
|
||||
```rust
|
||||
let config_max = Some(3u8);
|
||||
if let Some(max) = config_max {
|
||||
println!("The maximum is configured to be {max}");
|
||||
}
|
||||
```
|
||||
|
||||
if let is separated by an =
|
||||
the max binds to the value in option u8 then max can be used in the body of the if let
|
||||
|
||||
the block doesn't run if the pattern doesn't match exactly
|
||||
this reduces the amount of typing and boilerplate but you lose the exhaustive nature of match which is enforced
|
||||
|
||||
if let is a good refactor to when conciseness is preferred and working module/function is "done"
|
||||
|
||||
should be used when only matching against one pattern and only EVER ONE pattern
|
||||
|
||||
good to get rid of too verbose code
|
||||
|
Reference in New Issue
Block a user