Cause a compile error if a value is out of range

I have a macro that accepts 3 intagers. I want to cause a compile error if any one of them is out of range. However, when I use the compile_error! macro, it will always cause a compile error, even if that code is not reached (i.e if $r > 255 { compile_error!("value out of range");} will cause a compile error even if $r if 20). How would I do this?

Example macro:

macro_rules! example {
    ($r:expr) => {
     if $r > 255 {
         // code that will only cause a compile error if this code is reached
     }
    }
}

I'd use a panic during const evaluation for that. The error message is terrible though:

const fn ex(x: u32) {
    if x > 255 {
        panic!("no!");
    }
}

macro_rules! example {
    ($r:expr) => {
        const _: () = ex($r);
    };
}

fn main() {
    example!(2);
    example!(256);
}

Playground.


The error message is much better without a constant function I just realized:

macro_rules! example {
    ($r:expr) => {
        const _: () = {
            if $r > 255 {
                panic!("no!");
            }
        };
    };
}

fn main() {
    example!(2);
    example!(256);
}

Playground.

Thanks, this will work fine, although I wish I could get better error messages, especially in the IDE.

David Tolnay's case studies have an example with a const multiple of 8 assertion. Maybe you can get a better error message along similar lines: case-studies/bitfield-assertion/README.md at master · dtolnay/case-studies · GitHub

If the value is non constant, i.e generated at runtime, how do you expect the check to happen at compile time?

True, I forgot that I asked about that.

If you need a check at runtime, assert! would be a good choice

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.