【发布时间】:2016-09-15 18:00:16
【问题描述】:
在使用带有运算符重载的类时,我从一个简单的辅助方法中得到一个编译错误。这是一个独立的测试(根据我的真实代码进行了简化,但仍然证明了问题):
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 害怕什么。我认为这里没有任何危险。
【问题讨论】:
标签: rust