1

Trying to use T as generic parameter of a trait of another generic parameter this way:

pub trait Foo<T> {
    fn foo() -> T;
}

struct Bar<T, F: Foo<T>> {
    f: F,
}

fn main() {
}

Failing with:

error[E0392]: parameter `T` is never used
 --> src/main.rs:5:12
  |
5 | struct Bar<T, F: Foo<T>> {
  |            ^ unused parameter
  |
  = help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData`

The compiler advice is to use PhantomData:

use core::marker::PhantomData;

pub trait Foo<T> {
    fn foo() -> T;
}

struct Bar<T, F: Foo<T>> {
    f: F,
    t: PhantomData<T>,
}

fn main() {
}

Isn't there a more elegant way to deal with this than creating a fake field with a strangely named traits?

Luke Skywalker
  • 1,464
  • 3
  • 17
  • 35
  • It's a bit difficult to answer this question in the abstract. What characteristics should `struct Bar` have, should it implement `trait Foo`? – mallwright May 01 '21 at 17:44
  • No, it only needs a field that implements Foo. – Luke Skywalker May 01 '21 at 17:45
  • The answer in the duplicate question is actually pretty bad. As a consequence, one need to instantiate the fields with PhantomType each time you instantiate the structure. – Luke Skywalker May 01 '21 at 19:04

0 Answers0