Skip to content

Trait with type-dependent optional function forces implementation regardless of type #110219

Closed as duplicate of#20021
@cafce25

Description

@cafce25

I tried this code (from this Stack Overflow question):

trait Doable {}

trait MyTrait<T> {
    fn set_member(&mut self, member: T);

    fn do_member(&mut self)
    where
        T: Doable;
}

struct MyMember;
struct MyTraitStruct(Option<MyMember>);

impl MyTrait<MyMember> for MyTraitStruct {
    fn set_member(&mut self, member: MyMember) {
        todo!();
    }
}

I expected to see this happen:

It compiles as do_member is only available if the type parameter T implements Doable which MyMember doesn't.

Instead, this happened:

It doesn't compile with this error message:

error[E0046]: not all trait items implemented, missing: `do_member`
  --> main.rs:14:1
   |
6  | /     fn do_member(&mut self)
7  | |     where
8  | |         T: Doable;
   | |__________________- `do_member` from trait
...
14 |   impl MyTrait<MyMember> for MyTraitStruct {
   |   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `do_member` in implementation

Meta

rustc --version --verbose:

rustc 1.68.2 (9eb3afe9e 2023-03-27)
binary: rustc
commit-hash: 9eb3afe9ebe9c7d2b84b71002d44f4a0edac95e0
commit-date: 2023-03-27
host: x86_64-unknown-linux-gnu
release: 1.68.2
LLVM version: 15.0.6

and

rustc 1.70.0-nightly (9df3a39fb 2023-04-11)
binary: rustc
commit-hash: 9df3a39fb30575d808e70800f9fad5362aac57a2
commit-date: 2023-04-11
host: x86_64-unknown-linux-gnu
release: 1.70.0-nightly
LLVM version: 16.0.2

Workaround

To work around this one can simply implement the do_member method without the where clause:

impl MyTrait<MyMember> for MyTraitStruct {
    // [...]
    fn do_member(&mut self) {}
}

but it feels rather pointless to implement a method that's not callable and doesn't do anything.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-trait-systemArea: Trait systemC-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions