我在使用一个具有运算符重载的类时,从一个简单的帮助方法中得到了编译错误。这里是一个自包含的测试(从我的真实代码简化而来,但仍然演示了问题):
use std::ops::{Add, Sub, Neg, Mul, Div};
#[derive(Debug, Eq, PartialEq)]
pub struct Money {
cents: i64,
}
impl Money {
pub fn new(cents: i64) -> Money {
Money { cents: cents }
}
}
impl Add for Money {
type Output = Money;
fn add(self, other: Money) -> Money {
Money { cents: self.cents + other.cents }
}
}
impl Mul<Money> for f64 {
type Output = Money;
fn mul(self, rhs: Money) -> Money {
Money { cents: (self * rhs.cents as f64) as i64 }
}
}
#[derive(Debug)]
pub struct AbsOrPerc {
pub absolute: Money,
pub percent: f64,
}
impl AbsOrPerc {
pub fn new(abs: Money, perc: f64) -> AbsOrPerc {
AbsOrPerc {
absolute: abs,
percent: perc,
}
}
pub fn total(&self, basis: Money) -> Money {
// This works:
// Money::new((self.absolute.cents as f64 + self.percent * basis.cents as f64) as i64)
// This doesn't:
self.absolute + self.percent * basis
}
}
我正在尝试使用Rust 1.8编译这个程序,但是遇到了以下错误:
src/lib.rs:42:5: 42:9 error: cannot move out of borrowed content [E0507]
src/lib.rs:42 self.absolute + self.percent * basis
我已经阅读了Rust Book,特别是关于所有权和借用的部分。我在StackOverflow上阅读了许多与此相关的问题,例如:Cannot move out of borrowed content。虽然错误相同,但我认为我的问题不是重复的,因为情况不同。如果我知道其他问题如何适用于这个问题,我就不必问了。所以我的问题是:我该如何解决这个错误?我不想将
&self
更改为self
,因为这会引起其他问题。除了修复问题之外,我还想知道Rust害怕什么。我没有看到任何危险。