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?

  • pinknoise@lemmy.ml
    link
    fedilink
    arrow-up
    5
    ·
    edit-2
    3 years ago

    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;
    }
    
    • seahorse@lemmy.mlOP
      link
      fedilink
      arrow-up
      2
      ·
      3 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.

    • Ephera@lemmy.ml
      link
      fedilink
      arrow-up
      1
      ·
      3 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…