Impl添加类型别名元组(f64,f64)

时间:2017-12-27 13:20:58

标签: types rust

我有自定义类型Point

type Point = (f64, f64);

我想在一起添加两个Point,但我收到此错误

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)`

当我尝试实施Add时,我收到此错误:

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

是否可以为Add实施type?我应该使用struct吗?

1 个答案:

答案 0 :(得分:2)

不,您没有Point类型。遗憾的是,type关键字不会为现有类型创建新类型,而只会创建新名称(别名)。

要创建类型,请使用:

struct Point(f64, f64);
相关问题