The following snippet is from: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.fold
I understand that the generic type F
is a callable that implements FnMut
and takes two args: B
and Self::Item
, which is the item the iterator iterates over and the return type of this callable is B
. My question is with regards to B
's type. It is not specified, no constrains are described. Am I to understand that it can be any type?
fn fold<B, F>(self, init: B, f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
Yes, you are correct. So long as the type you give for init: B
is consistent with whatever you pass to f: F
then B
is otherwise unconstrained here (aside from the implicit Sized
requirement).
By "consistent with", I just mean that the B
in FnMut(B, Self::Item) -> B
is the same type as whatever you pass as init
.
For example
fn unsigned_adder(a: u32, b: u32) -> u32 {
a + b
}
some_u32_iterator.fold(0_i32, unsigned_adder);
is not consistent, because the function is expecting B
to be a u32
, but you've given a i32
as init
. Change to
some_u32_iterator.fold(0_u32, unsigned_adder);
and this is consistent.
(N.B. in the real world, type inference would sort you out in this example if you didn't put type suffixes on the int literals, but this is just to illustrate the point)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With