rust - How do I make my own adapter methods able to consume a trait object? -
i have trait has "adapter methods" consume method:
struct bar<t>(t); trait foo { fn make_bar(self) -> bar<self> self: sized { bar(self) } } impl foo u8 {} impl foo bool {} this modeled after iterator. when use box<iterator>, can still call iterator adapter methods map or filter:
fn main() { let = vec![1,2,3]; let b: box<iterator<item=u8>> = box::new(a.into_iter()); let c = b.map(|x| x * 2); z in c { println!("{}", z) } } however, methods i've defined don't work in same way:
fn main() { let a: box<foo> = box::new(42); a.make_bar(); } this fails errors
<anon>:16:7: 16:17 error: trait `core::marker::sized` not implemented type `foo` [e0277] <anon>:16 a.make_bar(); ^~~~~~~~~~ <anon>:16:7: 16:17 note: `foo` not have constant size known @ compile-time <anon>:16 a.make_bar(); ^~~~~~~~~~ it's absolutely correct foo not have size - it's trait. however, box<foo> should have size, understand it. iterator doing differently code?
because iterator object safe, trait object iterator implements iterator.
because impl<i: iterator + ?sized> iterator box<i>, boxed trait object box<iterator> implements iterator.
thus in case solution implement foo box<foo>. generic iterator’s (impl<t: ?sized + foo> foo box<t> { }) or specific (impl foo box<foo> { }).
Comments
Post a Comment