Best Practice for Pattern Matching a Complex Struct

Reference code: Rust Playground

Please is there a more idomatic way of implementing InitReq.location()?
Or, what's the best practice for extracting the latitude and longitude fields from the InitReq struct?

fn location(&self) -> (f32, f32) {
        match *self {
            InitReq {
                version:_,
                location:
                    GeoLocation {
                        loc:
                            Loc::Point(Ellipse {
                                center: Point { latitude, longitude },
                                semi_major_axis,
                                semi_minor_axis,
                                orientation,
                            }),
                        confidence,
                    },
            } => (latitude, longitude),
            _ => (0.0, 0.0)
        }
    }
}

These are the data types that make up InitReq:

struct InitReq {
    version: String,
    location: GeoLocation,
}

struct GeoLocation {
    loc: Loc,
    confidence: Option<i32>,
}

enum Loc {
    Point(Ellipse),
    Region(Polygon),
}

struct Ellipse {
    center: Point,
    semi_major_axis: Option<f32>,
    semi_minor_axis: Option<f32>,
    orientation: Option<f32>,
}

struct Point {
    latitude: f32,
    longitude: f32,
}

Thanks.

Here's how I'd write it:

fn location(&self) -> (f32, f32) {
    match self.location.loc {
        Loc::Point(Ellipse {
            center: Point { latitude, longitude },
            ..
        }) => (latitude, longitude),
        _ => (0.0, 0.0)
    }
}

Basically, use .. and field accesses (like self.location.loc) to avoid matching on parts of the data you don't care about.

6 Likes

Thanks cole-miller.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.