【发布时间】:2015-02-02 17:47:58
【问题描述】:
Add 特征定义为seen in the documentation。
为 Vector 实现它时,需要将其复制到 add 方法中以允许像 v1 + v2 这样的语法。如果 add 实现更改为支持借用引用并因此防止复制,则必须编写 &v1 + &v2,这是不可取的。
首选或最佳执行方式是什么?
(在 C++ 中,self 将是 const Vector<T>&,以及 rhs,但仍允许所需的 v1 + v2 语义。)
代码
为了完整起见,摘录我现在使用的代码
use std::num::Float;
use std::ops::Add;
#[derive(Debug, PartialEq, Eq, Copy)]
pub struct Vector<T: Float> {
x: T,
y: T,
z: T,
}
impl<T: Float> Add for Vector<T> {
type Output = Vector<T>;
// Probably it will be optimized to not actually copy self and rhs for each call !
#[inline(always)]
fn add(self, rhs: Vector<T>) -> Vector<T> {
Vector { x: self.x + rhs.x,
y: self.y + rhs.y,
z: self.z + rhs.z }
}
}
#[cfg(test)]
#[test]
fn basics() {
let v32 = Vector { x: 5.0f32, y: 4.0f32, z: 0.0f32 };
let v32_2 = v32 + v32;
assert_eq!(v32_2.x, v32.x + v32.x);
assert_eq!(v32_2.y, v32.y + v32.y);
assert_eq!(v32_2.z, v32.z + v32.z);
}
【问题讨论】:
-
我个人认为编译器在使用“拥有”值时应该能够做得更好,因为它可以随意移动它们。我通常担心会创建不必要的副本,但在这方面可能会有所不同。
标签: rust