In the Ada programming language, one can use the range constraint to declare that the value of a signed integer has to be within a minimum and maximum. An exception is triggered if not, for example.
What is the idiomatic way to achieve this in Rust?
In the Ada programming language, one can use the range constraint to declare that the value of a signed integer has to be within a minimum and maximum. An exception is triggered if not, for example.
What is the idiomatic way to achieve this in Rust?
Currently, compile-time ranged types are not implemented in Rust. There is a discussion at internals.rust-lang.org and several open GitHub issues: Range types for integers (or refinement types?) #671 and Numerical Constrained Types #1621. There is an experimental crate ranged_integers that prototypes ranged integers.
For a runtime implementation, you can define your type, e.g.,
struct RangedInt<const MIN: int, const MAX: int>(int);
and add checks in the operators' implementations.