1

I have a custom type Point

type Point = (f64, f64);

And I want to add two Points together but I get this error

error[E0368]: binary assignment operation `+=` cannot be applied to type `(f64, f64)`
   --> src/main.rs:119:21
    |
119 |                     force_map[&body.name] += force;
    |                     ---------------------^^^^^^^^^
    |                     |
    |                     cannot use `+=` on type `(f64, f64)`

And when I try implementing Add, I get this error:

39 | / impl Add for (f64, f64) {
40 | |     #[inline(always)]
41 | |     fn add(self, other: (f64, f64)) -> (f64, f64)  {
42 | |         // Probably it will be optimized to not actually copy self and rhs for each call !
43 | |         (self.0 + other.0, self.1 + other.1);
44 | |     }
45 | | }
   | |_^ impl doesn't use types inside crate
   |
   = note: the impl does not reference any types defined in this crate
   = note: define and implement a trait or new type instead

Is it possible to implement Add for a type? Should I use a struct instead?

Nevermore
  • 7,141
  • 5
  • 42
  • 64
  • Possible duplicate of [How do I implement a trait I don't own for a type I don't own?](https://stackoverflow.com/questions/25413201/how-do-i-implement-a-trait-i-dont-own-for-a-type-i-dont-own) – trent Dec 27 '17 at 14:27
  • Type aliases aren't new types, they're just shorthand for existing ones. [Advanced Types](https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html) (title is slightly misleading) – trent Dec 27 '17 at 14:29
  • Ok thanks, is it possible to impl Add on a type (f64, f64)? – Nevermore Dec 27 '17 at 14:34
  • You don't control the `Add` trait, and you don't control the type `(f64, f64)`, so no, the coherence rules forbid it. – trent Dec 27 '17 at 14:36
  • If you add that answer I can close the question, thank you – Nevermore Dec 27 '17 at 14:37
  • The answer is essentially "you can't implement a trait you don't own for a type you don't own", which is what the linked duplicate says. What clarification do you believe is necessary? – trent Dec 27 '17 at 14:44
  • I meant add it as an answer to the question so I can accept it as correct – Nevermore Dec 27 '17 at 14:45

1 Answers1

7

No, you don't have a Point type. The type keyword unfortunately does not create a new type, but only a new name (alias) for an existing type.

To create a type, use:

struct Point(f64, f64);
Kornel
  • 97,764
  • 37
  • 219
  • 309