演算子のオーバーロードでクラスを使用すると、簡単なヘルパーメソッドからコンパイルエラーが発生します。ここでは、自己完結型(私の実際のコードから簡略化し、それでも問題を実証する)テストです:オペレータのオーバーロードで "借用されたコンテンツから移動できません"
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
}
}
私は錆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
私は錆書と所有権と借用に関する部分を何度も読んだことがあります。私はこの質問についてStackOverflowの上ここでは、多くの質問、例えば:
Cannot move out of borrowed content
を読んだ私は、エラーが同じであるが、状況が異なっているので、自分の質問が重複しているとは思いません。また、私はこれらの他の質問がこの質問にどのように適用されたかを知っていれば、私は尋ねる必要はありません。 :-)
私の質問は:どのように私はこのエラーを解決できますか? &self
からself
に変更したくない場合は、他の問題が発生します。
問題を解決するだけでなく、私はRustが何を怖がっているかも知りたいと思います。私はここにどんな危険も見ない。
はhttp://stackoverflow.com/q/28595075/155423、http://stackoverflow.com/q/29926724/155423も参照してください、 http://stackoverflow.com/q/30974593/155423、http://stackoverflow.com/q/28527702/155423、http://stackoverflow.com/q/34621969/155423、およびhttp://stackoverflow.com/q/28843931/155423。 – Shepmaster