Common combinators

Let's look at some of the useful combinators that are available for both the Option and Result types:

map: This method allows you to transform the success value, T, to another value, U. The following is the type signature of map for the Option type:

pub fn map<U, F>(self, f: F) -> Option<U>
where F: FnOnce(T) -> U {
match self {
Some(x) => Some(f(x)),
None => None,
}
}

The following is the signature for the Result type:

pub fn map<U, F>(self, f: F) -> Option<U>
where F: FnOnce(T) -> U {
match self {
Ok(t) => Ok(f(t)),
Err(e) => Err(e)
}
}

This method's type signature can be read as follows: map is a generic method over U and F, and takes self by value. It then takes a parameter, f, of type F and returns an Option<U>, where F is constrained by the FnOnce trait, which has an input parameter, T, and a return type of U. Phew! That was quite a mouthful.

Let's make this simpler to understand. There are two parts to understand about the map method. First, it takes a parameter as self, which means the value on which this method is called is consumed after the call. Second, it takes in a parameter, f, of type F. This is a closure that's provided to map, which tells it how to do the conversion from T to U. The closure is generically represented as F and the where clause says that F is FnOnce(T) -> U. This is a special type of trait that is only applicable to closures and hence has a function like the signature of (T) -> U . The FnOnce prefix just means that this closure takes ownership of the input parameter, T, signifying that we can only call this closure once with T as T will be consumed upon invocation. We'll look into closures in more depth in Chapter 7, Advanced Concepts. The map method does nothing if the value is a failed value.

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

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