在下面的例子中,我想在数组中添加2个元素,在2个元素上有一个简单的加法,声明为内联,并从数组中访问。
use std::ops::Add;
use std::fmt;
struct Vector(f64, f64);
impl Add for Vector {
type Output = Vector;
fn add(self, _rhs: Vector) -> Vector {
Vector(self.0 + _rhs.0,
self.1 + _rhs.1)
}
}
impl fmt::Display for Vector {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.0, self.1)
}
}
fn main() {
let points: [Vector; 2] = [
Vector(1.0, 1.0),
Vector(5.0, 5.0),
];
/* Adding from an array fails somehow: */
// let v: Vector = Vector(1.0, 1.0) + Vector(5.0, 5.0); // This works!
let v: Vector = points[0] + points[1]; // This fails!
println!("Vector is {}\n", v);
}
出于某种原因,let v: Vector = points[0] + points[1];
会出错:
main.rs:37:21: 37:30 error: cannot move out of type `[Vector; 2]`, a non-copy fixed-size array [E0508]
main.rs:37 let v: Vector = points[0] + points[1]; // This fails!
如何避免此错误并对数组元素执行操作符重载操作?
答案 0 :(得分:1)
事实证明我需要添加对&Vector
类型的支持,然后将数组元素作为引用访问。
这是一个有效的例子:
use std::ops::Add;
use std::fmt;
struct Vector(f64, f64);
impl Add for Vector {
type Output = Vector;
fn add(self, _rhs: Vector) -> Vector {
Vector(self.0 + _rhs.0,
self.1 + _rhs.1)
}
}
impl<'a, 'b> Add<&'b Vector> for &'a Vector {
type Output = Vector;
fn add(self, _rhs: &'b Vector) -> Vector {
Vector(self.0 + _rhs.0,
self.1 + _rhs.1)
}
}
impl fmt::Display for Vector {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.0, self.1)
}
}
fn main() {
let points: [Vector; 2] = [
Vector(1.0, 1.0),
Vector(5.0, 5.0),
];
let v: Vector = &points[0] + &points[1];
println!("Vector is {}\n", v);
}
答案 1 :(得分:1)
您可以使Vector
元组结构从Copy
和Clone
特征派生。因此编译器可以从数组中复制元素。
use std::ops::Add;
use std::fmt;
#[derive(Copy, Clone)]
struct Vector(f64, f64);
impl Add for Vector {
type Output = Vector;
fn add(self, _rhs: Vector) -> Vector {
Vector(self.0 + _rhs.0,
self.1 + _rhs.1)
}
}
impl fmt::Display for Vector {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.0, self.1)
}
}
fn main() {
let points: [Vector; 2] = [
Vector(1.0, 1.0),
Vector(5.0, 5.0),
];
let v: Vector = points[0] + points[1];
println!("Vector is {}\n", v);
}