Skip to content

const assert in struct is not always evaluated #16004

@arifd

Description

@arifd

What it does

I would expect this not to compile because of the const assert, But it actually compiles fine, leading me to believe that I have a compile-time check in place, when actually I don't.

Advantage

Protects users from assuming that some const code is evaluated when it actually isnt.

Drawbacks

No response

Example

struct Foo<const C: char>;

impl<const C: char> Foo<C> {
    // This const check should fail for 'x', but it isn't evaluated.
    const _CHECK: () = assert!(C != 'x');

    fn new() -> Self {
        // Uncommenting the next line triggers the compile-time error as expected:
        // let _ = Self::CHECK;
        Foo
    }
}

fn main() {
    // This should fail (C == 'x'), but compiles fine.
    let _ = Foo::<'x'>::new();
    println!("it compiled!")
}

This also does not work:

struct Foo<const C: char>;

impl<const C: char> Foo<C> {
    const fn _check() {
        assert!(C != 'x');
    }
    
    fn new() -> Self {
        Foo
    }
}

fn main() {
    // This should fail (C == 'x'), but compiles fine.
    let _ = Foo::<'x'>::new();
    println!("it compiled!")
}

Comparison with existing lints

No response

Additional Context

I searched for duplicate issues: https://github.com/rust-lang/rust-clippy/issues?q=sort%3Aupdated-desc%20is%3Aissue%20is%3Aopen%20const%20struct%20eval

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions