Const Guards [docs.rs]
With const_guards you can express certain compile time constraints on rust's const_generics using the unstable generic_const_exprs feature.
Documentation
For documentation visit docs.rs.
Motivation
Consider the following usage of the first method on arrays from the standard library:
let array: = ;
let head: = array.first;
Would it be nice if we could just write
let head: & = array.first;
since the compiler should know this array has length 1 at this point.
With const guards we can express such as follows:
The index call on the array &array[0] cannot possible fail because we enforced the length of the array to be > 0 at compile time. We could now call it as follows
let array: = ;
let head: & = first;
while the case where the array is actually empty would fail to compile:
let array: [(); 0] = [(); 0];
let head: &() = first(&array);
Finally we could even express this as a trait to make it more accessable:
Though, as you can see, we need to introduce generics not introduced by the guarded item explicitly.
Implementation
Consider this simple example of a const guard:
and have a look at the expanded form:
;
}>: Protect,
Todo
- Improve error messages
- Write more tests