November 2017
Intermediate to advanced
264 pages
5h 45m
English
If you want to get a reference to a matched variable inside a match, use the ref keyword, as in the following example:
// see code in Chapter 7/code/ref.rs
fn main() {
let n = 42;
match n {
ref r => println!("Got a reference to {}", r),
}
let mut m = 42;
match m {
ref mut mr => {
println!("Got a mutable reference to {}", mr);
*mr = 43;
},
}
println!("m has changed to {}!", m);
}
This prints out the following output:
Got a reference to 42
Got a mutable reference to 42
m has changed to 43!
The r variable inside the match has the type &i32. In other words, the ref keyword creates a reference for use in the pattern. If you need a mutable reference, use ref mut.
We can also use ref to get a reference to a field of a struct ...
Read now
Unlock full access