'What is this specific `where` clause, is it a closure or function of some sort, or an enum?

I see two different things:

fn for_each<F>(self, f: F) where F: FnMut(Self::Item)

And:

fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering where I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering

One has the -> and the other doesn't. They are both called Fn, which makes me think it might be a closure. But I don't see any examples.

What do the where clauses mean exactly in this situation?



Solution 1:[1]

Rust annotates a return type with ->.

fn foo() -> i32 { ... }

When the function returns (), you can omit it for convenience. fn foo() -> () {} is the same as fn foo() {}.

The same thing happens with function pointers and closures: fn() -> () (a pointer to function returning ()) can be written as just fn(), and in the same manner, Fn() -> () (should be part of a generic constraint or dyn, a function/closure implementing the Fn trait) can be written as just Fn().

So,

fn for_each<F>(self, f: F) where F: FnMut(Self::Item)

Takes a function (or closure) that takes Self::Item and returns nothing. And

fn cmp_by<I, F>(self, other: I, cmp: F) -> Ordering where I: IntoIterator, F: FnMut(Self::Item, <I as IntoIterator>::Item) -> Ordering

Takes (besides the other iterator other) a function that takes Self::Item and I::Item and returns Ordering (std::cmp::Ordering).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chayim Friedman