Inner workings of Rust closures

Understand the inner workings of Rust closures by comparing the assembly code generated for closures returned as impl Fn versus Box<dyn Fn>.

impl Fn returning closure

pub fn make_quadratic(a: f64, b: f64, c: f64) -> impl Fn(f64) -> f64 {
    move |x| a*x*x + b*x + c
}

Box<dyn Fn> returning closure

pub fn make_quadratic_box(a: f64, b: f64, c: f64) -> Box<dyn Fn(f64) -> f64> {
    Box::new(make_quadratic(a, b, c))
}
2 Likes

Thanks. But for your actual book, I hope you cared a bit more about the text quality. From the very beginning of your blog post:

Closures can be called multiple times or can be called only once. Closures can be borrowed immutably, borrowed mutably, or ...

So I can call a closure once, or I can call it multiple times? Ok, but what do we really learn from this sentence?

And closures can be borrowed? The fact that I can borrow a whole closure is indeed new to me :slight_smile:

I guess the Rust experts might understand what you really mean, but for a broader audience, I would suggest to use a more precise and correct wording. The Rust language is complex and not that easy, so un-precise texts are not that helpful.

1 Like

Closures can be implemented using the Fn, FnMut, and FnOnce traits.

Is kinda misleading. I used closures a lot and never had to write impl FnOnce for MyClosure { ... }.
I guess what really was meant is that, closures, depending on their formulation, may implement the Fn, FnMut or FnOnce traits.

As for the mutability, while the wording is technically correct, it is not really helpful. Yes, you can borrow a closure mutably or immutably and a closure can take ownership of its arguments. But the one thing has little to do with the other.

2 Likes

You actually can't, since those traits are unstable. It would have been beneficial for me on certain occasions if I could implement Fn traits manually.

1 Like

Thank you for your suggestions. We’ve updated the page based on your feedback.

The book Rust Under the Hood underwent extensive editing to improve readability. While most of those revisions were already reflected in the Rust-to-assembly articles, we inadvertently missed this page.

As far as I understand, it is possible in nightly Rust.