#[derive(NumericEnum)]
Expand description
Derive macro that generates bidirectional conversion methods between enum variants and their numeric values. This automatically generates:
from_int<T: Into<usize>>(value: T) -> Option<Self>
: Converts a numeric value to the corresponding enum variantto_int(&self) -> usize
: Converts the enum variant back to its numeric value
ยงExamples
Basic usage:
use slang_derive::NumericEnum;
#[derive(Debug, PartialEq, NumericEnum)]
enum OpCode {
Add = 1,
Subtract = 2,
Multiply, // Implicit value: 3
Divide, // Implicit value: 4
}
// Convert from numeric values to enum variants:
let add_op = OpCode::from_int(1u8); // Some(OpCode::Add)
let add_op_usize = OpCode::from_int(1usize); // Some(OpCode::Add)
let invalid_op = OpCode::from_int(100u8); // None
Both explicit and implicit discriminant values are supported:
use slang_derive::NumericEnum;
#[derive(NumericEnum)]
enum Status {
Ok = 200,
NotFound = 404,
ServerError = 500,
Created = 201, // Note: order doesn't matter for explicit values
NotModified = 304,
BadRequest = 400,
}