Collection of trait instances - size cannot be known

I think I may need to do something with ?Sized to get this to work, but I haven't landed on the specific syntax yet. I have a feeling the solution isn't going to be pretty.

Why is that line necessary at all?

for item in self.items {
1 Like

why use a text variable?

        for item in self.items {
            writeln!(f, "{} ${}", item.get_description(), item.get_price())?;
1 Like

The items are all in a Box don't I have to dereference them in order to get the values out of them?

Good point! Also, I see that I needed to change the loop to for item in &self.items {.

I guess the unboxing happens automatically.

You don't need to get the values "out" of the Box at all, you can call object-safe trait methods on a reference to the trait object type. In this case auto-dereferencing kicks in, but you could do it "manually" as well:

        for boxed_item in self.items {
-            let item = *boxed_item;
+            let item = &*boxed_item;

Either way you do it the item doesn't need to be moved out of the Box.


Sidenote: If you switch to for item in &self.items, the type of item will now be &Box<dyn Priced>, but since auto-dereferencing happens as many times as necessary to find a valid receiver type, you still don't need to do anything special to handle the extra reference.