Editor's note: This code example is from a version of Rust prior to 1.0 and is not syntactically valid Rust 1.0 code. Updated versions of this code produce different errors, but the answers still contain valuable information.È possibile memorizzare un valore in una struttura attraverso un tratto?
Ho provato questo con e senza Box
, con e senza vite:
trait TraitToImpl {
fn do_something(self, val: i32);
}
struct Cont {
value: i32,
}
impl TraitToImpl for Cont {
fn do_something(self, val: i32) {
println!("{}", val);
}
}
struct StoreTrait<'a> {
field: Box<TraitToImpl + 'a>,
}
fn main() {
let cont = Box::new(Cont { value: 12 }) as Box<TraitToImpl>;
let a = StoreTrait { field: cont };
a.field.do_something(123);
}
Tutto quello che ottiene è questo errore:
error: cannot convert to a trait object because trait `TraitToImpl` is not object-safe
Grazie mille. Questo messaggio di errore non era chiaro per me. E, se capisco correttamente, è impossibile passare per valore attraverso il tratto. –