Verwirrt durch die Verschiebungssemantik von Strukturfeldern innerhalb einer Box
Wenn ich Folgendes tue, erhalte ich eine Fehlermeldung:
struct A;
struct B;
fn consume_a(_a: A) {}
fn consume_b(_b: B) {}
struct C(A, B);
impl C {
fn foo(self: Self) {
consume_a(self.0);
consume_b(self.1);
}
}
fn main() {
let c = Box::new(C(A, B));
// Consume internals
let _a = c.0;
let _b = c.1;
}
error[E0382]: use of moved value: `c`
--> src/main.rs:21:9
|
20 | let _a = c.0;
| -- value moved here
21 | let _b = c.1;
| ^^ value used here after move
|
= note: move occurs because `c.0` has type `A`, which does not implement the `Copy` trait
Ich kann das Gleiche erreichen (Verbrauch von Einbauten):
fn main() {
let c = Box::new(C(A, B));
c.foo();
}
Wie es oben funktioniert c.foo()
) bedeutet, dass ich nicht mehr in der Box bin. wie kann das passieren Keine der APIs inBox
ie Dokumentation von @ zeigt, dass ich den enthaltenen Wert als Typ erhalten kann (d. h., alle Methoden geben @ zurüc&T
oder&mut T
aber nichtT
)