rust - Newtype pattern of the combinations of Rc, RefCell and Box -
because don't want type code rc::new(refcell::new(box::new(mytype::new(args...))))
again , again, decided create newtype rcrefbox
below:
use std::rc::rc; use std::cell::refcell; struct rcrefbox<t>(rc<refcell<box<t>>>); impl<t> rcrefbox<t> { fn new(value: box<t>) -> rcrefbox<t> { rcrefbox(rc::new(refcell::new(value))) } } trait interface {} struct a; impl interface {} fn main() { let iface: rcrefbox<interface> = rcrefbox::new(box::new(a)); }
the code doesn't compile errors below: (playpen: http://is.gd/itir8q)
<anon>:19:16: 19:35 error: trait `core::marker::sized` not implemented type `interface` [e0277] <anon>:19 let iface: rcrefbox<interface> = rcrefbox::new(box::new(a)); ^~~~~~~~~~~~~~~~~~~ <anon>:19:16: 19:35 note: `interface` not have constant size known @ compile-time <anon>:19 let iface: rcrefbox<interface> = rcrefbox::new(box::new(a)); ^~~~~~~~~~~~~~~~~~~ <anon>:19:38: 19:51 error: trait `core::marker::sized` not implemented type `interface` [e0277] <anon>:19 let iface: rcrefbox<interface> = rcrefbox::new(box::new(a)); ^~~~~~~~~~~~~ <anon>:19:38: 19:51 note: `interface` not have constant size known @ compile-time <anon>:19 let iface: rcrefbox<interface> = rcrefbox::new(box::new(a)); ^~~~~~~~~~~~~ error: aborting due 2 previous errors
how can fix errors?
the problem not struct
itself, trait
pass.
trait objects dynamically sized objects (do not implement sized
).
normally, when specify bounds on generic type (t
here), constrain it, when sized
introduced decided applied as default bound because generic code deals sized
types , result t
alone means t: sized
.
there special "widening" bound "t
may not sized
": ?sized
, have apply if wish able take trait
objects. adding code:
use std::rc::rc; use std::cell::refcell; struct rcrefbox<t: ?sized>(rc<refcell<box<t>>>); // ?sized impl<t: ?sized> rcrefbox<t> { // ?sized fn new(value: box<t>) -> rcrefbox<t> { rcrefbox(rc::new(refcell::new(value))) } } trait interface {} struct a; impl interface {} fn main() { let iface: rcrefbox<interface> = rcrefbox::new(box::new(a)); }
makes work (http://is.gd/pszkk2).
Comments
Post a Comment