advancedPatterns
Pattern References
Match references with ref and ref mut patterns.
Pattern References
Match references with ref and ref mut patterns.
Difficulty
Advanced
Code
rust
fn main() {
let x = 5;
let y = &x;
match y {
&val => println!("matched ref: {}", val),
}
match *y {
val => println!("dereferenced: {}", val),
}
// ref pattern to borrow from a match
let name = String::from("Alice");
match name {
ref s => println!("borrowed: {}", s),
}
// name is still usable
println!("name: {}", name);
// ref mut
let mut data = vec![1, 2, 3];
match data[0] {
ref mut val => *val *= 10,
}
println!("data: {:?}", data);
}Explanation
ref/ref mut create references in patterns.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the patterns category to build a complete understanding of this topic.