October 2018
Beginner
180 pages
4h 48m
English
The IndexMut trait represents the abilities to assign to a contained value using the x[y] = z syntax. Like the Index trait, it lets us look up a contained data value by providing an index value, but it produces a mutable borrow of the contained value, which can be used to change it.
Implementing IndexMut looks like this:
pub struct IndexExample { first: u32, second: u32, third: u32, junk: u32,}impl<'a> IndexMut<&'a str> for IndexExample { fn index_mut(&mut self, index: &'a str) -> &mut u32 { match index { "first" => &mut self.first, "second" => &mut self.second, "third" => &mut self.third, _ => &mut self.junk, } }}
Notice that we've added a junk value to the IndexExample structure. We did that because there's no way to indicate that ...
Read now
Unlock full access