Index

The Index trait means that the data type can be used with the x[y] syntax, where a value is looked up inside of x based on the index value y.

When we implement Index, we need to identify what data type can be used for the index value, as well as what data type the operation returns, so the implementation looks like this:

pub struct IndexExample {
first: u32,
second: u32,
third: u32,
}

impl<'a> Index<&'a str> for IndexExample {
type Output = u32;

fn index(&self, index: &'a str) -> &u32 {
match index {
"first" => &self.first,
"second" => &self.second,
"third" => &self.third,
_ => &0,
}
}
}

We've used &str for the data type of the index, and were using u32 for the data type of the value. Using &str means that we need to be a little bit careful of lifetimes, but it's not too bad.

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

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