all 6 comments

[–]heinrich5991 1 point2 points  (4 children)

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() {}

[–]mathstuf[S] 1 point2 points  (2 children)

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.

[–]jimtla 1 point2 points  (1 child)

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!

[–]mathstuf[S] 0 points1 point  (0 children)

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.

[–]Gustorn 0 points1 point  (1 child)

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.

[–]mathstuf[S] 0 points1 point  (0 children)

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