this post was submitted on 12 Mar 2022
3 points (100.0% liked)

Rust Programming

8343 readers
14 users here now

founded 5 years ago
MODERATORS
 

I'm playing with the following code and can't seem to find an example where I can get the values of one of the coordinates.

enum Coordinates {
    Point1 { x: i32, y: i32 },
    Point2 { x: i32, y: i32 },
}
fn main() {
    let p1 = Coordinates::Point1{ x: 0, y: 45};
    let x = p1.x; //Doesn't work
}

How can I get the value of x or y?

top 3 comments
sorted by: hot top controversial new old
[–] [email protected] 5 points 2 years ago* (last edited 2 years ago) (2 children)

You need to figure out the variant before you can access any fields.

let x = match p1 {
  Coordinates::Point1 { x, .. } => x, // .. means "I don't care about the other fields"
  Coordinates::Point2 { x, .. } => x,
};

or if you only need to do stuff on one type of point

if let Coordinates::Point1 { x, _y } = p1 {
  // Do stuff with x or y here
  // _y (prefixed / replaced with _) means "I won't use that variable"
}

However it looks like what you want is a struct that contains an enum and the coordinates.

enum CoordinateKind {
  Point1,
  Point2,
}

struct Point {
  kind: CoordinateKind,
  x: i32,
  y: i32,
}

fn main() {
  let p = Point {
    kind: CoordinateKind::Point1,
    x: 0,
    y: 45,
  };

  let x = p.x;
}
[–] [email protected] 2 points 2 years ago

Thanks! Yeah, I'm not actually trying to do anything useful with this code. Just testing out the concepts that I'm reading about.

[–] [email protected] 1 points 2 years ago

Hmm, yeah, this is good. Coming from more object-oriented programming languages, my first intuition was to throw down a trait with those shared methods/fields, which then both coordinate-types implement, but that's rather clunky in Rust, since traits cannot define fields...