r/rust•
mathstuf

Using &self as &Trait from a default trait function implementation

Is there a way to have a default implementation of a trait reference itself as a reference to a trait? Here is a play.rust-lang.org link of what I'd like. Is there a better way to do something like this?

Thanks.

Posted Aug 3, 2016, 6:54 PM UTC

26
heinrich5991•

Not sure if that's what you want, but:

struct S<'a> {
  t: &'a T,
}

trait T {
  fn t(&self) -> &T where Self: Sized {
    self
  }

  fn s(&self) -> S where Self: Sized {
    S {
      t: self,
    }
  }
}

fn main() {}
2
mathstufOP•

Hmm, that at least compiles for unused code case, but if I have a &T, I can call neither t nor s since I don't know a Sized type for the trait to match the bounds.

New gist.

2
jimtla•

Here's a version with generic types, instead of storing trait objects: https://is.gd/owwRrc.

I don't know if this is the best way to do it, but it works so that's something!

2
mathstufOP•

Yeah, that'd work, but the struct being parameterized like that isn't so nice. The u/Gustom approach posted is probably the best way.

1
[deleted]•

[deleted]

1
Gustorn•

You cannot do this completely in default implementations. The &self pointer and the &Trait pointer are two different concepts: the latter is a fat pointer while the former is not. I think your best course of action is something like this if you have a lot of default implementations.

1
mathstufOP•

Thanks, that's pretty much what I came up with (though I called it _self_ref_hack :) ). as_trait sounds nicer.

1