How can I have an unused type parameter in a struct?

前端 未结 2 583
情书的邮戳
情书的邮戳 2020-12-21 12:41

I\'m trying to update some older code I wrote that basically looks like:

trait Foo{}

struct Bar>{
  b: B
}
相关标签:
2条回答
  • 2020-12-21 12:54

    Depending on how your real Foo is, you might be able to work with associated types instead, like this:

    trait Foo{ type T; }
    
    struct Bar<B: Foo> {
      b: B,
    }
    

    otherwise (if you do need to have the type parameter on Foo), PhantomData is indeed the way to go.

    You were not the only person finding PhantomData's docs confusing (see PhantomData is incomprehensible). As a result, the documentation for PhantomData has been recently improved by Steve Klabnik and now it does mention this scenario explicitly (and not just unsafe code).

    0 讨论(0)
  • 2020-12-21 12:59

    It seems that what you want is the following: for any type A, B must implement Foo<A>. That suggests that you rely on functionality of Foo that does not depend on the value of A, which means that you can change Foo to have an associated type rather than a type parameter.

    trait Foo<T> { }
    

    will become

    trait Foo {
        type T;
    }
    

    Then you can remove the A type parameter everywhere and require just B: Foo.

    To elaborate on PhantomData, it has nothing to do with unsafe code, it is used to determine variance of a type parameter when the compiler cannot infer it. See RFC 738 for more information on variance and PhantomData.

    0 讨论(0)
提交回复
热议问题