Why can we spawn a thread without storing it in a variable?

Why can we run this code ?

fn main() {
    thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
}

thread::spawn function returns a JoinHandle while main doesn't have return type or it's return type is (). Shouldn't this cause a error.

As documented for JoinHandle:

A JoinHandle detaches the associated thread when it is dropped, which means that there is no longer any handle to the thread and no way to join on it.


In case you’re wondering why a statement

f();

works for a function f not returning () (as is the case with thread::spawn(…): That’s just how Rust (any many other programming languages) are designed. Such a statement executes f() and discards (in case of Rust drops) the result.

You can see this documented e.g. in the reference:

An expression statement is one that evaluates an expression and ignores its result. As a rule, an expression statement's purpose is to trigger the effects of evaluating its expression.

1 Like

I somehow forgot that and thought the result is automatically returned.