Working code with &dyn Trait in struct field

Hello,

I'm not really new to Rust, but sometimes it just feels like I am even as time passes.
I've been able to produce a piece of code that works, but I'm not really sure it is valid or if could be written another way.
Could someone enlighten me please?
PS: I know the setters should not be available on a reference, it was more to check method availability when developping... final code wouldn't be written like that.

You're not alone in that!

I don't think there is an easier way if you really need the trait object. Some people use AsRef instead of Deref, but its basically the same.

So I only have some thoughts that are probably unhelpful, because they only suggest lessening the requirements, and you have probably already thought about them:

  • If you can do without a trait object then obviously you can remove all the traits.

  • If you can do away with the getters and setters, and the abstraction that flattens the properties, you can just access the fields directly and get rid of the use of Deref. The main reason I mention this is because accessing fields directly works much better with the borrow checker when trying to work with multiple properties at a time, especially if you're mutating.

1 Like

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.