There are many ways that work for modifying a value inside a match. It seems there are quite a few subtleties. Here we've collected a variety of solutions
All the examples are based on the following common code
#[derive(Debug)]
pub struct Packet {
blob_start:u32
}
pub fn get_latest_packet() -> Option<Packet> {
Some(Packet{ blob_start:10 })
}
main() {
let mut packet = get_latest_packet();
println!("packet = {}", packet);
// ... match goes here ...
println!("packet = {}", packet);
}
Matching on a mutable reference with mut ref
arms.
This was my original version
match &mut packet {
Some(ref mut packet) => { packet.blob_start = 0; }
None => { }
}
playground
It was pointed out that this only works due to match egronomics, and is equivalent to:
match &mut packet {
&mut Some(ref mut packet) => { packet.blob_start = 0; }
&mut None => { }
}
playground
Matching by value with a mut ref
arm
You don't need to pass a reference - you can just pass the value, and so long as you take a mutable reference to the contained packet object it works.
match packet {
Some(ref mut packet) => { packet.blob_start = 0; }
None => { }
}
playground
Matching with on mutable reference, with default arms
match &mut packet {
Some(packet) => { packet.blob_start = 0; }
None => { }
}
playground
Again this seems to rely on the match ergonomics details.
Matching by value with mut
arm.
If you don't need to access the packet option after the match you can use this:
match packet {
Some(mut packet) => {
packet.blob.start = 0;
// ... do something with the packet ...
}
}
In this case, you don't need the mut
on the packet option either.
playground