Using isize vs usize

If this occurs a lot, it may be time for a simple expression macro to encapsulate this. I've used ix!(). If your indexing range is less than half of usize then this definition might work for you:

macro_rules! ix {
    ($e: expr) => {
        let val = $e;
        assert!(val >= 0);  // Checks that e is integer and non-negative
        (val as usize)
    }
}

Credits: If memory serves, @HadrienG suggested this to me when I had a similar query.
Edit: "non-negative", rather than "positive".

1 Like