Why I can use dyn Trait directly inside struct definition?

Why can I use the dyn Trait as the field type declaration inside the struct? I usually use &dyn trait, today I forgot put the & at the beginning of type when defining a struct. But rust doesn't complain it.

struct Test {
    folder: dyn Iterator<Item = String>,
}

And I tried to make a new method of it

impl Test {
    fn new(folder: &dyn Iterator<Item = String>) -> Self {
        Self { folder: *folder }
    }
}

It gives me the error I expected that

|     fn new(folder: &dyn Iterator<Item = String>) -> Self {
|                                                     ^^^^ doesn't have a size known at compile-time

But why doesn't Rust give an error when I define the struct before making the method for it? Does Rust know the size in the definition? Thanks.

1 Like

Generally speaking,

  • there's a desire to support unsized locals to some extent in the future
  • there's a desire to better support custom DSTs (dynamically sized types) in the future

So there are places where unsized types don't necessarily make sense today, but they don't throw errors until you try to use them because they don't want to require Sized in those places.

But as it turns out, while it requires unsafe, you can make use of custom DSTs to some extent today, so your example definitely shouldn't error. Here's an example of dyn Trait in a struct definition being put to use.

(Edit: Updated playground with 'static bound as it's otherwise unsound...)

4 Likes

Thanks! Cannot wait for that future to come.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.