rust

Why Not Just Use Fn, FnMut, or FnOnce as Types?


Closures in Rust already fall into one of three well-defined categories (Fn, FnMut, and FnOnce) based on their capture behavior.

If there are only these three possible types, why bother with impl? Why not directly use them as types instead of impl Trait?


Solution

  • If there are only these three possible types

    This is not correct. Fn, FnMut, and FnOnce are not types, they are traits. In fact, they cannot be just types.

    While any ordinary fn you define can be represented as a simple pointer, closures are a completely different thing. They can capture their environment, which in practice means that they can use the variables defined near them. This also means that they need to store these variables somewhere, as you can't really know when exactly the closure will be executed. Every closure might want to capture different types of variables, all having different sizes, so there can't be a one-size-fits-all type that could contain any sort of "context" that you might possibly use. Hence, through the compiler magic, an unnamable type is created, which you can confirm with a simple code snippet:

    let mut x = 5;
    let f = || {
        x += 1;
    };
    
    println!("size_of({}) = {}", std::any::type_name_of_val(&f), std::mem::size_of_val(&f));
    

    This prints:

    size_of(playground::main::{{closure}}) = 8
    

    Under the hood, what happens in the above code is something close to this:

    let mut x = 5;
    struct Closure<'a> {
        // closure context
        x: &'a mut i32,
    }
    impl FnOnce<()> for Closure<'_> {
        type Output = ();
        extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
            // closure body
            *self.x += 1;
        }
    }
    let f = Closure { x: &mut x };
    
    // now it can be called:
    f();
    

    The closure object in this case must contain a mutable reference to the variable it modifies, so the closure type is 8 bytes long (on a 64-bit platform). You might want to experiment a little with different closures capturing different things and notice that the closure type size directly depends on the variables it captures.


    See also: How do Rust closures work and how does it execute a closure?