Using generic types as function return values

Within an implementation block that has generic type parameters, we can use those parameter names as part of function return values, too.

Here is an example function that uses generic type parameter names in its return data type:

    fn get_ref(&self, key: K) -> Result<&V, String> {
if key == self.key {
return Ok(&self.value);
}
else if key < self.key {
match self.lesser {
None => {
return Err("No such key".to_string());
}
Some(ref lesser) => {
return lesser.get_ref(key);
}
}
}
else {
match self.greater {
None => {
return Err("No such key".to_string());
}
Some(ref greater) => {
return greater.get_ref(key);
}
}
}
}

This function looks up a key in the binary tree, and returns an immutable borrow of the associated value, or an error message if the key is not present in the tree.

It's structured very similarly to the set function we saw before, but since we're not changing anything or asking for a mutable borrow, self can be a plain old immutable borrow as well.

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

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