Where without generics

Behold this struct:

pub struct Battery(Device)
where
    Device: BatteryDevice;

Is this basically a fancy way of writing:

pub struct Battery(BatteryDevice);

.. or is there more to it?

1 Like

Here's a minimized example:

pub trait BatteryDevice {}

pub struct Device;

impl BatteryDevice for Device {}

pub struct Battery(Device)
where
    Device: BatteryDevice;

Playground

Looks like this trait bound is simply a way to enforce more adequate compiler errors in case when Device is (erroneously) not implementing BatteryDevice: you can check that, if you comment out the implementation, compiler will complain:

error[E0277]: the trait bound `Device: BatteryDevice` is not satisfied
 --> src/lib.rs:7:1
  |
7 | / pub struct Battery(Device)
8 | | where
9 | |     Device: BatteryDevice;
  | |__________________________^ the trait `BatteryDevice` is not implemented for `Device`
  |
  = help: see issue #48214

This might be helpful, because in practice Device is a plaform-dependent reexprort, and, if the implementation is accidentally omitted for one of cases, compiler will hint on the real problem, not on the place where the implementation ought to be used.

11 Likes

Side note: the declaration is

pub struct NewType(OtherConcreteType)
where
    OtherConcreteType: Trait;

where as

pub struct NewType(Trait);

would be deprecated syntax for

pub struct NewType(dyn Trait);

and those aren't the same thing (unless SomeOtherType is a type alias for dyn Trait), because dyn Trait is it's own distinct, single, concrete type.

8 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.