|| operator in new() for Actix

On the hello world example for Actix: https://actix.rs/

There is a || operator in the new call. I am having a hard time understanding what this is for since there are no operands on the left hand side.

#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
    App::new()
        .route("/", web::get().to(greet))
        .route("/{name}", web::get().to(greet))
})
.bind("127.0.0.1:8080")?
.run()
.await
}

The || in this position is actually not an "or" operator but the (empty) parameter list of a closure. In general, closures look like e.g. this:

fn main() {
    let f = |x| x+1;
    let a = 1;
    let b = f(a);
    
    let g = || String::new();
    
    let x: String = g();
    let y: String = g();
    
    let foo = || {
        let var = 42;
        var
    };
    let forty_two: i32 = foo();
    
    let say_hello = | | println!("hello!");
    say_hello();
    say_hello();
    
    let sum_with_elaborate_types = |x: u64, y: u64| -> u64 { x + y };
    let result = sum_with_elaborate_types(42, 1337);
    
    let mut x = 1;
    let mut increment_x = || x += 1;
    increment_x();
    increment_x();
    increment_x();
    assert_eq!(x, 4);
}
2 Likes

That makes perfect sense. Thank you!