0

I don't quite understand when/how a function can use bounds of types Fn, FnOnce, FnMut. Can someone explain in what scenario these would be used and how one would use them?

As I understand it, I can create a function like this:

struct Dog {
    name: String,
}

struct Cat {
    name: String,
}


fn foo(a: impl FnOnce(Dog) -> Cat) {
    // call a once
}

But why would I pass a function into another function? Is there some kind of advantage of doing so such as bypassing function visibility, etc.?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
SPQR
  • 29
  • 4
  • Look up the strategy pattern – Daniel A. White Apr 05 '23 at 22:32
  • Also: [What is the point of function pointers?](https://stackoverflow.com/q/2592137/364696) This isn't language-specific, Rust just splits the types of functions up into broad categories to support the various compile-time safety features it provides, but simply being able to pass functions around is useful in all languages. – ShadowRanger Apr 05 '23 at 22:33
  • 1
    For some other search terms, in functional languages the concept is called "higher order functions". – cafce25 Apr 05 '23 at 22:43
  • Look at some of the functions in std::iter — they paint a pretty compelling picture of why you'd need to pass a function to another function. – BallpointBen Apr 06 '23 at 05:16

0 Answers0