0

I want to create types, and implementations of std::ops::Add such that:

add(Position, Displacement) -> Position
add(Displacement, Displacement) -> Displacement

The purpose is to make nonsense operations, such as adding two positions, cause compile-time errors.

How can I do this, given that add()'s signature is: fn add(self, other: Self) -> Self::Output?

2
  • 2
    This is not the correct Add::add() signature. The correct one lets you do what you want. Commented Jan 16 at 19:40
  • @EugeneSh. Thanks for pointing that out. Commented Jan 16 at 19:53

1 Answer 1

1

Got it to work, thanks to Eugene Sh.

impl Add<Displacement> for Position {
    type Output = Position;

    fn add(self, rhs: Displacement) -> Self::Output {
        Position::new(self.x + rhs.x, self.y + rhs.y)
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.