snippetrustMajor
How do you access enum values in Rust?
Viewed 0 times
enumyouhowaccessrustvalues
Problem
struct Point {
x: f64,
y: f64,
}
enum Shape {
Circle(Point, f64),
Rectangle(Point, Point),
}
let my_shape = Shape::Circle(Point { x: 0.0, y: 0.0 }, 10.0);I want to print out
circle's second property, which is 10.0 here.I tried
my_shape.last and my_shape.second, but neither worked.What should I do in order to print out 10.0 in this case?
Solution
You can use pattern matching:
Example output:
struct Point {
x: f64,
y: f64,
}
enum Shape {
Circle(Point, f64),
Rectangle(Point, Point),
}
fn main() {
let my_shape = Shape::Circle(Point { x: 0.0, y: 0.0 }, 10.0);
match my_shape {
Shape::Circle(_, value) => println!("value: {}", value),
_ => println!("Something else"),
}
}Example output:
value: 10
Code Snippets
struct Point {
x: f64,
y: f64,
}
enum Shape {
Circle(Point, f64),
Rectangle(Point, Point),
}
fn main() {
let my_shape = Shape::Circle(Point { x: 0.0, y: 0.0 }, 10.0);
match my_shape {
Shape::Circle(_, value) => println!("value: {}", value),
_ => println!("Something else"),
}
}Context
Stack Overflow Q#9109872, score: 70
Revisions (0)
No revisions yet.