enum Point {
Nothing,
TuplePoint(i32, i32),
StructPoint {
x: i32,
y: i32
}
}
fn get_point(n: u8) -> Point {
match n {
1 => Point::TuplePoint(-1, 1),
2 => Point::StructPoint {
x: -1,
y: 1
},
_ => Point::Nothing
}
}
fn main() {
let p = get_point(2);
match p {
/* match nothing variant */ => println!("no point"),
/* match tuplepoint variant */ => println!("x is {} and y is {}", x, y),
/* match structpoint variant */ => println!("x is {} and y is {}", x, y),
}
}
I think you accidentally created a new topic instead of replying to the post. You can press the Reply button to reply.
Welcome to the forum, @NzongangFotsing! It seems you posted your topic with the same name as this other topic, even though that topic isn’t related to this one. I’ll answer your question:
/* snip unchanged code */
fn main() {
let p = get_point(2);
match p {
Point::Nothing => println!("no point"),
Point::TuplePoint(x, y) => println!("x is {} and y is {}", x, y),
Point::StructPoint { x, y } => println!("x is {} and y is {}", x, y),
}
}
This is destructuring an enum
in match
, which is explained in the Book, or in Rust by Example.
Your example has the same code in both destructuring match
arms, so you can write it like this with an or pattern:
match p {
Point::Nothing => println!("no point"),
Point::TuplePoint(x, y) | Point::StructPoint { x, y } => {
println!("x is {} and y is {}", x, y);
},
}
1 Like