Hi.
One of the things that drew me to Rust is that it prevents crashes from NULL pointers, errors in allocation, etc. So I was a bit surprised when I discovered that something like
for i in 0 .. nr_items - 4 { ... }
panic!s when nr_items, an unsigned value, is less than 4.
So first a question: is there any way to remedy this? Casting to a signed type doesn't seem very desirable, but perhaps it's the only way.
Second: a slightly wild thought. Would it be possible to guarantee that this error wouldn't occur, and call it an error when the guarantee cannot be given? A simple option would be to automatically add a test around the for statement, skipping it when nr_items < 4 (if there is no information about the bounds on nr_items), but that would only help loops.
Another option would be a way to state that nr_items is at least 4 through the type system. If that is not guaranteed, the above construction fails at compile time instead of at run time. This
let mut nr_items: 4..100 = f(something);
would do the trick, or if nr_items was declared as a usize,
match nr_items {
4..100 => ... nr_items - 4 ...
_ => ()
}
Then the panic! would only have to occur when a cast is made that violates the type's bounds. I know that inferring such bounds across computations is error prone, but it's possible in some cases; in others, the programmer would need to help the compiler. Just a thought.