Match Moves Out Of Owned Enum Variants
Matching an owned enum moves payloads out of variants; matching a reference borrows them. Both shapes appear here, with use-after-move left to the compiler.
Code
#[derive(Debug)]
enum Order {
Draft,
Placed { id: u32, label: String },
}
// 按值接收:match by value 会把 String 载荷 move 出枚举变体
fn finish(order: Order) -> String {
match order {
Order::Draft => String::from("nothing to finish"),
Order::Placed { id, label } => {
// label 已被 move 进分支:返回它,而不是引用它
format!("order {id} closed: {label}")
}
}
}
// 借用接收:match &Order 时绑定自动变为引用,不发生 move
fn label_of(order: &Order) -> &str {
match order {
Order::Draft => "draft",
Order::Placed { label, .. } => label,
}
}
fn main() {
let order = Order::Placed { id: 7, label: String::from("bulk renew") };
// 借用路径走完,order 仍然完整可用
println!("{}", label_of(&order));
println!("still usable: {:?}", order);
// 所有权整体交给 finish,此后 order 不能再使用(编译器强制)
println!("{}", finish(order));
}How it works
Count the functions finish, label_of and main as the entire surface area of Match Moves Out Of Owned Enum Variants.
The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.
Using it
The primary signature is fn finish(order: Order) -> String
The demo output is labeled (still usable:), so every printed line maps back to its originating operation.
There are 2 calls inside main — label_of and finish — executed top to bottom.
Key statements
fn label_of(order: &Order) -> &str {
match order {
Order::Draft => "draft",
Order::Placed { label, .. } => label,
}
}
fn finish(order: Order) -> String {
match order {
Order::Draft => String::from("nothing to finish"),
Order::Placed { id, label } => {
// label 已被 move 进分支:返回它,而不是引用它
format!("order {id} closed: {label}")
}
}
}
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Match Moves Out Of Owned Enum Variants print when run?
- Running the file directly is enough — expect labeled output lines such as `still usable:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.