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.
A JoinHandledetaches 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 fnot 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.
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.