TheEnvironmentalist
TheEnvironmentalist

Reputation: 2852

Why does `thread::JoinHandle<T>` have a type parameter?

In Rust, the thread::JoinHandle<T> type included with the standard library has the type parameter T. However, it doesn't seem that T is actually set or used for anything.

Indeed, Rust's own documentation mostly just uses thread::JoinHandle<_> whenever it needs to assign a JoinHandle<T> to something. What does this T actually do?

Upvotes: 4

Views: 1631

Answers (1)

Alex Huszagh
Alex Huszagh

Reputation: 14614

It's the type that's returned from the threaded code. You can always auto-deduce the type, and you generally don't want to write the type explicitly. There's a few examples in the documentation for join, which returns a Result<T>.

The following example is from the documentation:

spawn returns a JoinHandle, which when joined returns the Result.

let computation = thread::spawn(|| { 
    // Some expensive computation.
    42
});
let result = computation.join().unwrap();
println!("{}", result);

Upvotes: 5

Related Questions