Skip to content

Inconsistent availability of constant fields as const generic values #92776

Closed
@jamesmunns

Description

@jamesmunns
Member

I tried this code:

struct Example {
    foo: usize
}

const EXAMPLE: Example = Example { foo: 42 };

struct Other {
    // works
    field: [u8; EXAMPLE.foo],
}

struct Wow<const N: usize> {
    field: [u8; N]
}

impl<const N: usize> Wow<N> {
    fn new() -> Self {
        Self {
            field: [0u8; N]
        }
    }
}

fn main() {
    // works
    let x = [0u8; EXAMPLE.foo];
    
    // doesn't work
    let y: Wow<EXAMPLE.foo> = Wow::new();
    
    // does work
    const EXAMPLE_FOO: usize = EXAMPLE.foo;
    // does work
    let z: Wow<EXAMPLE_FOO> = Wow::new();
}

I expected to see this happen:

I expect all uses of EXAMPLE.foo to be acceptable

Instead, this happened: let y: Wow<EXAMPLE.foo> = Wow::new(); is rejected with the following error:

error: expected one of `!`, `(`, `+`, `,`, `::`, `:`, `<`, `=`, or `>`, found `.`
  --> src/main.rs:29:23
   |
29 |     let y: Wow<EXAMPLE.foo> = Wow::new();
   |         -             ^ expected one of 9 possible tokens
   |         |
   |         while parsing the type for `y`

error: could not compile `playground` due to previous error

Meta

This is present in the current stable (1.57.0), as well as the latest nightly (1.60.0 2022-01-10)

Backtrace

<backtrace>

Activity

jamesmunns

jamesmunns commented on Jan 11, 2022

@jamesmunns
MemberAuthor

As a quick update, this DOES work when adding curly braces:

// does work
let y: Wow<{EXAMPLE.foo}> = Wow::new();

So I suppose this might be considered a diagnostics bug instead/as well, as this was not mentioned in the error output.

compiler-errors

compiler-errors commented on Jan 13, 2022

@compiler-errors
Member

As a quick update, this DOES work when adding curly braces

Yeah, I think this is a diagnostics issue.

We should probably recover parsing <foo.bar> and suggest wrapping in { .. }. We already do this in other cases with const generics.

added a commit that references this issue on Feb 26, 2022

Auto merge of rust-lang#92884 - compiler-errors:const-generic-expr-re…

7c3331c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @jamesmunns@compiler-errors

      Issue actions

        Inconsistent availability of constant fields as const generic values · Issue #92776 · rust-lang/rust