IndexMut

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 an index value doesn't map to a valid contained value; if the index_mut function gets called, is has to return a mutable borrow of the correct type, and that borrow has to have a long enough lifetime as well. Adding a junk value to the data structure is a simple way of achieving that, though there are other approaches that would save memory.

Any type that implements IndexMut has to implement Index as well, and the index and index_mut functions have to return a borrow and a mutable borrow of the same data type, respectively.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.150.231