how can I match the value of an enum two times?
The problems seems to occur, if the value of an enum is "consumed" in a match. I don't understand why I get the error message "use of moved value ... value used here after move" -- see code below
I would understand to get the error if I return just the value but I am returning a clone of value and still get the error.
// Here a simple enum
enum SomeEnum {
X(String),
}
// Then later in some function ...
// Test Enum which works
let x = SomeEnum::X(String::from(("a")));
let x_val1 = match x {
SomeEnum::X(_) => 1
};
println!("x_val1 = {}", x_val1);
let x_val2 = match x {
SomeEnum::X(_) => 1
};
println!("x_val2 = {}", x_val2);
// Test Enum which does not work
let y = SomeEnum::X(String::from(("b")));
let y_val1 = match y {
SomeEnum::X(value) => value.clone()
};
println!("y_val1 = {}", y_val1);
// Does not compile, here I get error message ...
// use of moved value
//
// value used here after move
let y_val2 = match y {
SomeEnum::X(value) => value.clone()
};
println!("y_val2 = {}", y_val2);
By default, match
statements consume all they can, so the value will be moved and owned. The compiler already suggests a workaround:
help: borrow this field in the pattern to avoid moving
y.0
SomeEnum::X(ref value) => value.clone(),
See keyword ref:
Using the ref keyword, the value is only borrowed, not moved, making it available for use after the match statement:
What you currently do is letting the match
take ownership and then clone. But at that point, ownership is already "gone". So the compiler complains about it.
But you can have it even simple in today’s Rust. If you match on a borrowed value match &y
, then all bindings will attempt to borrow as well. This was introduced with match ergonomics.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments