为类型别名元组 (f64, f64) 添加 Impl [英] Impl Add for type alias tuple (f64, f64)

查看:33
本文介绍了为类型别名元组 (f64, f64) 添加 Impl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类型 Point

I have a custom type Point

type Point = (f64, f64);

我想将两个 Point 加在一起,但出现此错误

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

当我尝试实现 Add 时,出现此错误:

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

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

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

推荐答案

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

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.

要创建类型,请使用:

struct Point(f64, f64);

这篇关于为类型别名元组 (f64, f64) 添加 Impl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆