Type sig of folding over collection<T>

fn fold_a<Accum, F: Fn(Accum, &T) -> Accum> (&self, accum: Accum, f: F) -> Accum {

fn fold_b<Accum, F: Fn(&mut Accum, &T)> (&self, accum: Accum, f: F) -> Accum {

Is there a preference of one style over the other ?

I'd say go with the value-based signature Fn(Accum, &T) -> Accum. It will work with references, but the other variant won't work with non-references, and it can be more inconvenient to call inside your implementation too.

While you are at it, you can change the signature to FnMut(Accum, &T) -> Accum as well. Also consider whether you can provide &mut T instead of &T while it doesn't break your API.

The point of Iterator::fold is that it gives ownership of the accumulator. If only &mut to it is needed, there's no need to thread it along all the time (in fact it can actually be slower) and just using Iterator::for_each with an FnMut closure is sufficient.

So I'd look at that closely and see whether those same lessons apply to your API. (And maybe see if you can just implement Iterator instead of making your own fold...)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.