Sub topic 3
Indexing and Operator Design in Rust
Assume you know structs, traits, generics, borrowing, and associated types. Rust exposes indexing and comparisons through traits, so custom types can behave like standard collections and values.
Indexing with `Index` and `IndexMut`
Index powers value[index]. Its method returns a reference to an associated Output type. IndexMut adds mutable indexing for assignments.
use std::ops::{Index, IndexMut};
struct Grid {
width: usize,
cells: Vec<i32>,
}
impl Index<(usize, usize)> for Grid {
type Output = i32;
fn index(&self, (row, col): (usize, usize)) -> &i32 {
&self.cells[row * self.width + col]
}
}
impl IndexMut<(usize, usize)> for Grid {
fn index_mut(&mut self, (row, col): (usize, usize)) -> &mut i32 {
&mut self.cells[row * self.width + col]
}
}
fn main() {
let mut grid = Grid { width: 3, cells: vec![0; 6] };
grid[(1, 2)] = 7;
assert_eq!(grid[(1, 2)], 7);
}The implementation must decide how invalid indexes behave. A normal vector access panics; a custom type may validate an index before returning.
Comparison Operators
== and != come from PartialEq. Ordering operators come from PartialOrd, whose partial_cmp returns an Option<Ordering>. Deriving these traits is usually safest. Floating-point values can be unordered because of NaN, so PartialOrd is different from total ordering.
Generic Operator Bounds
Generic code can require the exact operator behavior it needs:
use std::ops::Add;
fn sum<T>(values: &[T]) -> T
where
T: Copy + Default + Add<Output = T>,
{
values.iter().copied().fold(T::default(), |a, b| a + b)
}The Orphan Rule
You may implement a trait when either the trait or the type is defined in your crate. You cannot implement a foreign trait for two foreign types, such as Add<String> for Vec<u8>. A local wrapper type gives you control.
Bitwise and Shift Traits
BitAnd, BitOr, BitXor, Not, Shl, and Shr provide &, |, ^, !, <<, and >>. Use them for naturally bit-oriented types, such as flags or bit sets.
Reducing Repetition
macro_rules! can generate similar implementations:
macro_rules! impl_flag_op {
($trait:ident, $method:ident, $op:tt) => {
impl $trait for Flags {
type Output = Flags;
fn $method(self, rhs: Flags) -> Flags {
Flags(self.0 $op rhs.0)
}
}
};
}The macro requires a local Flags type and the corresponding trait in scope.
Exercise
Why does an indexing implementation return a reference instead of an owned value?
Show answer
Indexing must support borrowing and assignment through IndexMut without unnecessarily moving the stored element.