/ Mehrere Implementierungen der Eigenschaft "Hinzufügen" für denselben Typ - Eigenschaften "Rost"

Mehrere Implementierungen des Attributs Hinzufügen für den gleichen Typ - Rost, Merkmale

Ich versuche etwas sehr einfaches zu machen:

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);
}

Rust Compile mag meinen Code nicht und sagt:

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       }

Letztendlich möchte ich meinem Typ A ein Int hinzufügen:

let x: A = A { a: 10 } + A { a: 20 };
let y: A = A { a: 10 } + 20i;
let z: A = A 10i + { a: 20 };

Was ist der beste Ansatz?

Antworten:

4 für die Antwort № 1

Aktualisieren:

JA, das kannst du jetzt umsetzen!

Wie? In ähnlicher Weise wie unten:

use std::ops::Add;

#[derive(Debug)]
struct A {
a: i32,
}


impl Add<i32> for A {
type Output = A;

fn add(self, _rhs: i32) -> A {
A { a : self.a + _rhs }
}
}

impl Add<A> for A {
type Output = A;

fn add(self, _rhs: A) -> A {
A { a : self.a + _rhs.a }
}
}

fn main() {
let x = A { a: 10 } + A { a: 20 };
let y = A { a: 40 } + 2;

println!("x: {:?}ny: {:?}", x, y);
}

Erläuterung. Sehen Sie, wenn Sie schreiben

let x = A { a: 10 } + A { a: 20 };

Rust sucht alle Merkmale hinzufügen hinzugefügt for A. Problem ist, weil zwei definiert sind: impl Add<A, A> for A und impl Add<int, A> for A Rust ist "unsicher", welchen man nehmen soll. Zitieren Sie mich nicht, weil Rust-Compiler-Interna nicht meine Sache sind, aber ich denke, das Rust-Team wollte vermeiden, den Preis für Multi-Dispatch zu zahlen.

Ihre Lösung ist entweder
A) Fügen Sie ein weiteres Merkmal hinzu Antworten das wird den Zusatz für Sie tun, wie im Beispiel angegeben.
B) Warten Sie, bis die assoziativen Typen gelandet sind. ( Ausgabe Nr. 17307 )
C) aufgeben impl Add<int, A> for A.

Ich denke, Sie wollen Multi-Dispatch, die bald landen sollte. Sieh dir das an RFC # 195 für Details.