Rust deref coersion doesn't work for nested types

Viewed 111

I'm running into an issue where the compiler seems unable to coerce the desired type by recursive deref-coersion. I have the following code:

use std::ops::Deref;

struct MyStruct<T> {
    data: T
}

impl<T> Deref for MyStruct<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}

pub trait MyTrait {
    fn bar(&self);
}

impl<T> MyTrait for MyStruct<T> {
    fn bar(&self) {}
}

fn foo<T: MyTrait>(arg: T) {
    //
}

fn main() {
    let data = Box::new(MyStruct { data: 42 });
    foo(&data);
}

And I get the following error:

error[E0277]: the trait bound `&Box<MyStruct<{integer}>>: MyTrait` is not satisfied
  --> src\bin\main.rs:36:9
   |
36 |     foo(&data);
   |         ^^^^^ the trait `MyTrait` is not implemented for `&Box<MyStruct<{integer}>>`
   |
note: required by a bound in `foo`
  --> src\bin\main.rs:30:11
   |
30 | fn foo<T: MyTrait>(arg: T) {
   |           ^^^^^^^ required by this bound in `foo`

My expectation is that the compiler would be able to recursively deref Box<MyStruct> until it encountered a type that satisfied the trait requirement (MyTrait) for the argument.

How might I be able to achieve this without modifying the calling syntax of foo(&data)?

0 Answers
Related