rust-lang / rust-lang/rfcs

Inherent trait implementations

Open
#1,880 27 comments 48 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-lang
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

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.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue proposes changing Rust trait-method visibility and names no files, tests, entry points, or concrete acceptance criteria. Start by reviewing the proposal and its 27-comment discussion to determine whether the idea has a viable design; done would require an agreed language design and implementation plan.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.