Skip to content

HRTB with const generics fails in Edition 2021 but works in Edition 2024 (backward compatibility issue) #148311

@Rafael2022-prog

Description

@Rafael2022-prog

Rust Version:

rustc 1.93.0-nightly (292be5c 2025-10-29)

Code:

#![feature(generic_const_exprs)]

trait HRTBTrait<const N: usize> {

type Output;

fn hrtb_method<F>(&self, f: F) -> Self::Output

where

F: for<'a> Fn(&'a [u8; N]) -> &'a [u8; N] + 'static;

}

struct HRTBImpl<const N: usize>;

impl<const N: usize> HRTBTrait<N> for HRTBImpl<N>

where

[(); N]:,

{

type Output = ();

fn hrtb_method<F>(&self, f: F) -> Self::Output

where

F: for<'a> Fn(&'a [u8; N]) -> &'a [u8; N] + 'static,

{

let array: [u8; N] = [0; N];

let _result = f(&array);

()

}

}

fn identity<const N: usize>(input: &[u8; N]) -> &[u8; N] {

input

}

fn main() {

let impl_instance = HRTBImpl::<32>;

let _future = impl_instance.hrtb_method(identity); // ERROR HERE

}

Current Output:


error[E0308]: mismatched types

--> test.rs:33:19

|

33 |     let _future = impl_instance.hrtb_method(identity);

|                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ one type is more general than the other

|

= note: expected reference `&_`

found reference `&'a _`

note: the lifetime requirement is introduced here

--> test.rs:7:39

|

7 |         F: for<'a> Fn(&'a [u8; N]) -> &'a [u8; N] + 'static;

|                                       ^^^^^^^^^^^

error: aborting due to 1 previous error

Expected Behavior:

The code should compile successfully as the identity function signature matches the HRTB requirement exactly.

Additional Context:

This appears to be a regression that was present in Rust Edition 2021 but has been fixed in the default Edition 2024. However, the bug still affects code that explicitly uses --edition 2021, which is concerning for backward compatibility.

The issue affects any code that combines:

  1. HRTB (for<'a> syntax)

  2. Const generics in trait definitions

  3. Function parameters with lifetime-dependent array types

  4. Explicit use of Rust Edition 2021

This prevents compilation of valid generic code patterns when using older editions, affecting backward compatibility for cryptographic and systems programming contexts.

Reproduction command: rustc +nightly --edition 2021 test.rs

Note: Bug does NOT occur with default edition 2024: rustc +nightly test.rs

Platform: x86_64-pc-windows-msvc

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions