<story><title>Why Rust closures are somewhat hard</title><url>https://stevedonovan.github.io/rustifications/2018/08/18/rust-closures-are-hard.html</url></story><parent_chain></parent_chain><comment><author>Animats</author><text>There&amp;#x27;s a lot of confusion about this.&lt;p&gt;A lambda is just a function without a name. (This feature tends to come with special syntax, although it doesn&amp;#x27;t have to.)&lt;p&gt;A nested function is a function defined inside another function which can access the variables of the enclosing function. (A nested function can be a lambda, but it doesn&amp;#x27;t have to be. Some languages have named nested functions. A lambda doesn&amp;#x27;t have to be a nested function; it doesn&amp;#x27;t have to pull in any variables from an outer scope.)&lt;p&gt;A closure is a nested function which can outlive the outer function, keeping its data alive. (A closure can be named, the usual case in Python and Javascript, or anonymous. So a closure need not be a lambda.)&lt;p&gt;Closures are easy to implement in garbage collected languages, but hard in explicitly allocated ones, because extending the lifetime of the imported data gets complicated.&lt;p&gt;So the options are:&lt;p&gt;- Lambda without any external data access  -- typical use, comparison function for a sort.&lt;p&gt;- Lambda with external data access, but not outliving its enclosing function - typical use, iteration expression&lt;p&gt;- Named function with no external data access. Typical use, a local function in languages that don&amp;#x27;t do local functions well, such as C.&lt;p&gt;- Named function with external data access, not outliving its enclosing function. Typical use, internal function within a function to avoid passing extra parameters.&lt;p&gt;- Named function with external data access, outliving its enclosing function. A true closure, but not a lambda. Typical use, saving state for a callback in Javascript by passing the function to something that will save it and invoke it later. An object, really. This was how LISP did objects.&lt;p&gt;- Lambda function with external data access, outliving its enclosing function. A true closure. Same uses as above, but in different languages.&lt;p&gt;Most languages offer some subset of these six options.</text></comment>
<story><title>Why Rust closures are somewhat hard</title><url>https://stevedonovan.github.io/rustifications/2018/08/18/rust-closures-are-hard.html</url></story><parent_chain></parent_chain><comment><author>cobbzilla</author><text>The fact that you can even do stuff like this in Rust is amazing. It’s simultaneously: relatively clean code, very efficient and type-safe. I like it.</text></comment>