Created
December 5, 2024 10:20
-
-
Save Nadrieril/f459dbdda3f3cae30dbecd285a2157f0 to your computer and use it in GitHub Desktop.
Lesser-known rust pattern-matching features
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Destructuring assignment | |
fn fibonacci(n: u64) -> u64 { | |
let mut a = 1; | |
let mut b = 1; | |
for _ in 0..n { | |
(a, b) = (a + b, a); | |
} | |
b | |
} | |
// Slice patterns | |
fn print_slice(slice: &[u32]) { | |
while let [x, rest @ ..] = slice { | |
// rest: &[u32] | |
println!("Found {x}, {} items remaining", | |
rest.len()); | |
slice = rest; | |
} | |
} | |
// Range patterns | |
match x { | |
0..42 => ..., | |
0..=42 => ..., | |
..42 => ..., | |
42.. => ..., | |
} | |
// Constants in patterns | |
const BEST_VALUE: u32 = 42; | |
match x { | |
BEST_VALUE => ..., | |
0..BEST_VALUE => ..., | |
_ => ..., | |
} | |
// Match ergonomics | |
fn as_ref(x: &Option<T>) -> Option<&T> { | |
match x { | |
Some(x) => Some(x), // x: &T | |
None => None, | |
} | |
} | |
// Or patterns | |
match ... { | |
Some(true) => ..., | |
Some(false) | None => ..., | |
} | |
match ... { | |
Some(12 | 42) => ..., | |
_ => ..., | |
} | |
// Let-else | |
fn do_something(vec: Vec<u32>) -> bool { | |
let Some(x) = vec.first() else { | |
return false | |
}; | |
x >= 42 | |
} | |
// same as: | |
fn do_something(vec: Vec<u32>) -> bool { | |
if let Some(x) = vec.first() { | |
x >= 42 | |
} else { | |
return false | |
} | |
} | |
// Let chains (unstable, see https://github.com/rust-lang/rust/issues/53667) | |
if let Some(foo) = vec.first() | |
&& let [x, y, ..] = f(foo) | |
&& x >= 1 { | |
... | |
} | |
// Guard patterns (future, see https://github.com/rust-lang/rust/issues/129967) | |
match x { | |
Some(vec) if vec.is_empty() | |
| None => ..., | |
_ => ..., | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment