Pattern matching in Rust moves ownership of values into the pattern bindings by default, meaning the original variable can no longer be used after the match. To access the data without taking ownership, use the ref keyword to bind by reference or & to match against a reference directly.
enum Message {
Quit,
Move { x: i32, y: i32 },
}
let msg = Message::Move { x: 10, y: 20 };
// Takes ownership of the fields
match msg {
Message::Move { x, y } => println!("Moved to {}, {}", x, y),
_ => (),
}
// msg is now unusable here
// Borrowing instead of moving
let msg2 = Message::Move { x: 10, y: 20 };
match msg2 {
Message::Move { ref x, ref y } => println!("Borrowed: {}, {}", x, y),
_ => (),
}
// msg2 is still usable here