Search code examples
rusttraits

Delegation of trait impl only possible in nightly?


I want to delegate the implementation of the trait Foo to the contents of a (single element) container Bar, only when its generic contents already implements Foo (Bar<T: Foo>).

pub trait Foo {
    fn foo(&self) -> u8;
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq)]
pub struct Bar<T> {
    wrapped: T
}

impl Foo for Bar<T: Foo> {
    fn foo(&self) -> u8 {
        self.wrapped.foo()
    }
}

results in:

error[E0658]: associated type bounds are unstable
  --> /home/fadedbee/test.rs:26:18
   |
26 | impl Foo for Bar<T: Foo> {
   |                  ^^^^^^
   |
   = note: see issue #52662 <https://github.com/rust-lang/rust/issues/52662> for more information
   = help: add `#![feature(associated_type_bounds)]` to the crate attributes to enable

Is this only possible in nightly, or am I just using the wrong syntax?


Solution

  • Just a minor syntactic difference.

    impl<T : Foo> Foo for Bar<T> {
      fn foo(&self) -> u8 {
        self.wrapped.foo()
      }
    }
    

    The impl needs to introduce the type variable and then we use it in Bar. The above is equivalent to the more verbose

    impl<T> Foo for Bar<T> where T : Foo {
      fn foo(&self) -> u8 {
        self.wrapped.foo()
      }
    }
    

    In either case, the impl introduces the type variable.