Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read that function declaration

Tags:

rust

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,
like image 589
Deborah C Avatar asked Sep 03 '25 16:09

Deborah C


1 Answers

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)

like image 195
JMAA Avatar answered Sep 05 '25 14:09

JMAA