我試圖做這樣的事情很簡單的幾種實現方式:添加特徵爲同類型
fn main() {
#[deriving(Show)]
struct A {
a: int
}
impl Add<A, A> for A {
fn add(&self, other: &A) -> A {
A { a: self.a + other.a }
}
}
impl Add<int, A> for A {
fn add(&self, v: &int) -> A {
A { a: self.a + *v }
}
}
let x = A { a: 10 } + A { a: 20 };
println!("x: {}", x);
}
鏽編譯不喜歡我的代碼,並說:
src/sandbox.rs:20:12: 20:37 error: multiple applicable methods in scope [E0034]
src/sandbox.rs:20 let x = A { a: 10 } + A { a: 20 };
^~~~~~~~~~~~~~~~~~~~~~~~~
src/sandbox.rs:8:7: 10:8 note: candidate #1 is `main::A.Add<A, A>::add`
src/sandbox.rs:8 fn add(&self, other: &A) -> A {
src/sandbox.rs:9 A { a: self.a + other.a }
src/sandbox.rs:10 }
src/sandbox.rs:14:7: 16:8 note: candidate #2 is `main::A.Add<int, A>::add`
src/sandbox.rs:14 fn add(&self, v: &int) -> A {
src/sandbox.rs:15 A { a: self.a + *v }
src/sandbox.rs:16 }
最終我想添加一個int到我的類型A那樣:
let x: A = A { a: 10 } + A { a: 20 };
let y: A = A { a: 10 } + 20i;
let z: A = A 10i + { a: 20 };
什麼是最好的方法?
對於相同類型的許多特徵實現不支持,您可以使用此解決方法:http://stackoverflow.com/questions/24594374/overload-operators-with-different-rhs-type – snf 2014-10-16 20:33:44