Can functions be passed as arguments? For example, in JavaScript you can pass a function as an argument like this:
setInterval(function() { /*...*/ }, 1000);
Can functions be passed as arguments? For example, in JavaScript you can pass a function as an argument like this:
setInterval(function() { /*...*/ }, 1000);
They are first class. In contrast to JavaScript, Rust has two types - functions and closures.
Anonymous functions like
function() {}
in JavaScript do exist in Rust, and you can define them using the closure syntaxNotice that the argument and return types are inferred!
Whether they are first class or not demands a little more exploration. By default, closed-over variables will be borrowed by the function. You can specify that those values be moved into the function using a
move
closure:Importantly, closures that do not reference their environment, which includes
move
closures, do not require references to the stack frame that created them. Since their sizes aren't known, they aren't first class objects by themselves.You can
Box
a closure and return it as a trait object of theFn
trait.This answer a brief summary of what's in the book which explains how closures are desugared and how they interact with the environment.
It seems that it is the case, as described in the reference manual.
It also tried the following, which pass a closure and function in the same way: