Skip to content

Const values in traits not treated the same as global const values for const_err #89063

Closed
@bhgomes

Description

@bhgomes

The following code only reports one error instead of two:

#[derive(Clone, Copy, Debug)]
pub struct GreaterThanTwo(u16);

impl GreaterThanTwo {
    /// Builds a [`GreaterThanTwo`] who's inner value is at least `2`.
    pub const fn new(value: u16) -> Self {
        let _  = value - 2;
        Self(value)
    }
}

pub trait Constants {
    const COUNT: GreaterThanTwo;
}

pub struct Config;

impl Constants for Config {
    const COUNT: GreaterThanTwo = GreaterThanTwo::new(0);
}

pub const OTHER_COUNT: GreaterThanTwo = GreaterThanTwo::new(0);

The COUNT variable inside of the Constants implementation does not trigger a const_err error where OTHER_COUNT does.

error: any use of this value will cause an error
  --> src/lib.rs:7:18
   |
7  |         let _  = value - 2;
   |                  ^^^^^^^^^
   |                  |
   |                  attempt to compute `0_u16 - 2_u16`, which would overflow
   |                  inside `GreaterThanTwo::new` at src/lib.rs:7:18
   |                  inside `OTHER_COUNT` at src/lib.rs:22:41
...
22 | pub const OTHER_COUNT: GreaterThanTwo = GreaterThanTwo::new(0);
   | ---------------------------------------------------------------
   |
   = note: `#[deny(const_err)]` on by default
   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
   = note: for more information, see issue #71800 <https://github.com/rust-lang/rust/issues/71800>

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

Rust Playground Link

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