Returning `&mut Self` for method chaining not working from traits?

Hello,

I've got a silly question, as I ran into the following code not to be working:

trait OutputInterface {
    fn set_verbosity(&mut self, verbosity: Verbosity) -> &mut Self;
}

the trait 'output::output_interface::OutputInterface' cannot be made into an object

Returning dyn OutputInterface however does work:

trait OutputInterface {
    fn set_verbosity(&mut self, verbosity: Verbosity) -> &mut dyn OutputInterface;
}

Can someone explain me why returning &mut Self doesn't work in my trait?

Thanks,
Raymond

This is because when you create an OutputInterface trait object, the compiler forgets what the underlying type is, and when you return &mut Self, you are returning a reference to that underlying type. Since the compiler forgot what the underlying type is, the compiler is unable to interact with a &mut Self.

When you return a mutable reference to a trait object instead, the compiler doesn't need to know what the underlying type behind the reference is because the reference itself includes the information necessary to use the reference.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.