Crate at

Source
Expand description

Various helpers for indexing slices. This crate provides three methods for indexing slices: at, ref_at, and mut_at. These methods offer a few benefits over standard indexing:

  • They work for any integer type, rather than just usize
  • They support Pythonesque negative indices; for example, nums.at(-1) returns the last element
  • You explicitly specify whether you’re indexing by value (for Copy types), reference, or mutable reference, rather than the compiler “magically” choosing the right kind of access
  • You can disable all bounds checks across the entire program by activating the unsafe-unchecked feature; this is not recommended unless you absolutely need the performance gains

All this happens with zero runtime overhead compared to standard indexing. However, note that checking the validity of signed types is slightly more complex than for a usize due to negative indexing. Signed indexing does not incur any overhead when the index is known at compile time.

§Examples

use at::{At, RefAt, MutAt};

let mut v = vec![8, 2, 1, 0];
assert_eq!(v.at(-1), 0);
assert_eq!(v.ref_at(2), &1);
assert_eq!(v.mut_at(-3), &mut 2);