book
book copied to clipboard
Fixes statement about FnOnce in trait bounds.
This part of the book kind of confused me
The trait bound specified on the generic type F is FnOnce() -> T, which means F must be able to be called at least once, take no arguments, and return a T. Using FnOnce in the trait bound expresses the constraint that unwrap_or_else is only going to call f at most one time. In the body of unwrap_or_else, we can see that if the Option is Some, f won’t be called. If the Option is None, f will be called once. Because all closures implement FnOnce, unwrap_or_else accepts the most different kinds of closures and is as flexible as it can be.
I think the second and last sentences contradict each other.
Here's the code example it refers to
impl<T> Option<T> {
pub fn unwrap_or_else<F>(self, f: F) -> T
where
F: FnOnce() -> T
{
match self {
Some(x) => x,
None => f(),
}
}
}
As I understand it, unwrap_or_else() will certainly call the closure only once, but not because of the trait bound. It's just the way its code is.