rust - Is it possible to store a value in a struct through a trait? -
editor's note: code example version of rust prior 1.0 , not syntactically valid rust 1.0 code. updated versions of code produce different errors, answers still contain valuable information.
i tried , without box
, , without lifetimes:
trait traittoimpl { fn do_something(self, val: i32); } struct cont { value: i32, } impl traittoimpl 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 }) box<traittoimpl>; let = storetrait { field: cont }; a.field.do_something(123); }
all error:
error: cannot convert trait object because trait `traittoimpl` not object-safe
the problem is, error message says, trait traittoimpl
not object safe. is, not safe use particular trait through reference (i.e. &traittoimpl
or box<traittoimpl>
.
specifically, do_something
method takes self
value. consider: how compiler call method on cont
that's been placed in box<traittoimpl>
? has copy value argument of type cont
(which impl
expects), call has work any type of any size might implement traittoimpl
!
practical upshot: if have trait contains by-value self
, or generics, cannot used via reference. @ point call happens, compiler no longer has enough information generate necessary code.
maybe try taking &self
instead? :)
Comments
Post a Comment