Skip to content

Inherent trait implementations #1880

@frewsxcv

Description

@frewsxcv

I've been working a lot with traits lately with this rust-geo pull request.

In that pull request, it splits up concrete geospatial types and geospatial operations. A simplified example:

struct PointType {
    x: f32,
    y: f32,
}

trait PointTrait {
    fn x(&self) -> f32;
    fn y(&self) -> f32;
    fn distance<P: PointTrait>(&self, other: P) -> f32 {
        // distance algorithm
    }
}

impl PointTrait for PointType {
    fn x(&self) -> f32 { self.x }
    fn y(&self) -> f32 { self.y }
}

Now, if someone ever wanted to use this, they'd have to import both the type and the trait:

use geo::{PointType, PointTrait};
let p1 = PointType { x: 1, y: 1 };
let p2 = PointType { x: 2, y: 2 };
println!("distance: {}", p1.distance(p2));

Most of the time, the user is always going to want the associated methods associated with PointType, so it's a little unfortunate that the user has to add another import whenever they want this functionality.

It'd be cool if I could make a trait implementation as exposed so that the triat methods are always available on that specific type. Something like:

exposed impl PointTrait for PointType {
    fn x(&self) -> f32 { self.x }
    fn y(&self) -> f32 { self.y }
}

(There's probably a better keyword to use here than exposed, or maybe some other way to indicate this.)

Then the user can just do:

use geo::PointType;
let p1 = PointType { x: 1, y: 1 };
let p2 = PointType { x: 2, y: 2 };
println!("distance: {}", p1.distance(p2));

I haven't thought too long about this, so I might be overlooking something here. I don't feel strongly at all about this, just expressing a thought.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions