Skip to content

#[derive(Clone)] fails for HRTB function type taking an associated type #122622

Closed
@theemathas

Description

@theemathas

The following code does not compile, even though it probably should:

trait SomeTrait {
    type SomeType<'a>;
}

#[derive(Clone)]
struct Foo<T: SomeTrait> {
    x: for<'a> fn(T::SomeType<'a>)
}

(playground link)

The error message on rust 1.76.0 stable is:

   Compiling playground v0.0.1 (/playground)
error[E0261]: use of undeclared lifetime name `'a`
 --> src/lib.rs:7:31
  |
7 |     x: for<'a> fn(T::SomeType<'a>)
  |                               ^^ undeclared lifetime
  |
  = note: for more information on higher-ranked polymorphism, visit https://doc.rust-lang.org/nomicon/hrtb.html
help: consider making the bound lifetime-generic with a new `'a` lifetime
  |
5 | #[derive(for<'a> Clone)]
  |          +++++++
help: consider introducing lifetime `'a` here
  |
6 | struct Foo<'a, T: SomeTrait> {
  |            +++

For more information about this error, try `rustc --explain E0261`.
error: could not compile `playground` (lib) due to 1 previous error

(The note being incorrect is a separate bug, already filed as #107694.)

The error message on rust 1.78.0-nightly (2024-03-16 766bdce744d531267d53) is:

   Compiling playground v0.0.1 (/playground)
error[E0261]: use of undeclared lifetime name `'a`
 --> src/lib.rs:7:31
  |
6 | struct Foo<T: SomeTrait> {
  |            - help: consider introducing lifetime `'a` here: `'a,`
7 |     x: for<'a> fn(T::SomeType<'a>)
  |                               ^^ undeclared lifetime
  |
  = note: for more information on higher-ranked polymorphism, visit https://doc.rust-lang.org/nomicon/hrtb.html

For more information about this error, try `rustc --explain E0261`.
error: could not compile `playground` (lib) due to 1 previous error

Note that manually implementing a Clone compiles fine without any errors:

trait SomeTrait {
    type SomeType<'a>;
}

struct Foo<T: SomeTrait> {
    x: for<'a> fn(T::SomeType<'a>)
}

impl<T: SomeTrait> Clone for Foo<T> {
    fn clone(&self) -> Self {
        Self {
            x: self.x
        }
    }
}

(playground link)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-attributesArea: Attributes (`#[…]`, `#![…]`)A-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions