Difference between Closures and Functions

IS there any difference between closures and functions, apart from the fact that they (closures) can be passed anonymously without variables into functions/closures?

That's not the difference, since function items and function pointers can be passed around too.

The real difference is the fact that the function pointer is just that - a pointer to the memory, nothing more; and the function item is purely a compile-time concept, which is essentially converted into hardcoded call wherever possible (or into function pointer, if this is necessary). Closures, on the other hand, can "close over" some data - you can think of them as (arbitrary) structs, which have a special syntax to call one of their methods (a method of the one of Fn* traits, to be precise).

1 Like

I hope I am not being rude, but could you please explain that in simpler terms. I am new to Rust, and low-level programming in general.

A function can also be passed like a closure can:

fn takes_closure<F>(f: F)
where
    F: Fn(u32) -> u32,
{
    println!("{}", f(100));
}

fn my_func(i: u32) -> u32{
    i + 1
}

fn main() {
    takes_closure(my_func);
}

However the thing that only a closure can that a function can't is to access local variables.

fn takes_closure<F>(f: F)
where
    F: Fn(u32) -> u32,
{
    println!("{}", f(100));
}

fn main() {
    let i = 10;
    
    takes_closure(|j| {
        i + j
    });
}

Notice how it can access the local variable i. Doing this is called "capturing the environment".

4 Likes