Rust - Associated type with generics

Viewed 48

I am trying to implement serde::Deserialize on an external type (which uses type params) using the newtype pattern. In the process I need to implement the visitor trait which has an associated type.

However I am getting unconstrained type parameter errors and I am unsure how to fix these in this case:

pub struct Money<'a, T: rusty_money::FormattableCurrency>(rusty_money::Money<'a, T>);
struct MoneyVisitor;

impl<'de, 'a, T> Visitor<'de> for MoneyVisitor { // unconstrained type parameter for 'a and T
    type Value = Money<'a, T>;

    //...
}

If I add type params to MoneyVisitor too I get errors about them being unused since it is an empty struct.

1 Answers

You'll likely want to:

  • add generics to MoneyVisitor
  • use PhantomData to prevent the compiler error about unused generics
struct MoneyVisitor<'a, T>(std::marker::PhantomData<&'a T>);

PhantomData is a special type which is allowed to have generic parameters that it doesn't use. So if you want a struct to "encode" some types, even if it has no actual fields of that type, you'll need to use it.

Then when you come to implement the trait, you can use those generics in the definition to avoid the "unconstrained type parameter" errors

impl<'de, 'a, T> Visitor<'de> for MoneyVisitor<'a, T> {  parameter for 'a and T
    type Value = Money<'a, T>;

    // ...
}

Here's a playground which has this code.

Related