Can I build a new type which wraps i32 with some custom constraints?


Is it possible to create a type that only allows values greater than some specific value(say 2) which is enforced at compile time?

Sure, start with something like this:

struct GreaterThanTwo(i32);

impl GreaterThanTwo {
    pub const fn new(value : i32) -> Option<Self> {
        if value > 2 {
        } else {

That will still entail a check for whether the input is greater than 2 when you first create a value of type GreaterThanTwo, but new() is const so you could do it at compile time (although const unwrap() is still unstable). A macro with compile_error! could also work for handling literals. You could also provide a new_unchecked(), possibly making it unsafe, that bypasses the check.

After that, you want to implement the relevant operator traits from std::ops and as many methods from i32 as you want, mainly deferring to the implementations on i32, but you will also need to decide how you are going to handle situations where values less than 2 may result from an operation.

Of course, it may be better to start with u32 if greater than 2 is the constraint you actually want.


Thanks! I will try it.

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.