Skip to content

Inconsistent availability of constant fields as const generic values #92776

Closed
@jamesmunns

Description

@jamesmunns

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>

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

    No branches or pull requests

    Issue actions