How to define unsupported enum value like invalid_atomic_ordering

I got an error atomic loads cannot have "Release" or "AcqRel" ordering in the code below:

use std::sync::atomic::{AtomicUsize, Ordering};

fn main() {
    let counter = AtomicUsize::new(0);
    println!("Result: {}", counter.load(Ordering::AcqRel));
}

I wonder if it's possible apply this on a custom Enum?

enum E1 {
    A1,
    A2,
    A3,
}

// How to let compiler report error when pass constant value E1::A3?
fn some_function(v: E1) {
    if let E1::A3 = v{
        panic!("A3 not supported")
    }
    // do something
}

You can't.

1 Like

invalid-atomic-ordering is a lint. That is, there is a static code analysis tool (like clippy[1] or in this case rustc) which looks at your source code and spots certain patterns that are deemed unidiomatic or faulty. I don't think you can get something akin to invalid-atomic-ordering for your own enum.

What I'd look into instead would be to split E1 into two enums, using the type system to prevent someone passing the wrong value at compile time:

enum E1 {
    A1,
    A2,
}

enum E2 {
    E1(E1),
    A3,
}

// A3 can never be passed to `some_function`
fn some_function(v: E1) {
}

Or document the panicking behaviour well in your docs and let the panic happen at run time.


  1. Which was where invalid-atomic-ordering originally came from. â†Šī¸Ž

2 Likes