diff options
author | George Malayil Philip <georgemp@users.noreply.github.com> | 2020-09-06 02:14:42 +0530 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-09-05 22:44:42 +0200 |
commit | d74eabc7d795afa8ca2cd9170977d47131e12ee0 (patch) | |
tree | 5962cf76e68815365cd453de0b26abd911849887 /tokio/src/runtime | |
parent | 6260ed907bff17abe2b889c2f87e7086284ddf05 (diff) |
runtime: mention on JoinHandle that the generic parameter is the return type (#2819)
Diffstat (limited to 'tokio/src/runtime')
-rw-r--r-- | tokio/src/runtime/task/join.rs | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/tokio/src/runtime/task/join.rs b/tokio/src/runtime/task/join.rs index 3c4aabb2..0529aa29 100644 --- a/tokio/src/runtime/task/join.rs +++ b/tokio/src/runtime/task/join.rs @@ -45,6 +45,71 @@ doc_rt_core! { /// # } /// ``` /// + /// The generic parameter `T` in `JoinHandle<T>` is the return type of the spawned task. + /// If the return value is an i32, the join handle has type `JoinHandle<i32>`: + /// + /// ``` + /// use tokio::task; + /// + /// # async fn doc() { + /// let join_handle: task::JoinHandle<i32> = task::spawn(async { + /// 5 + 3 + /// }); + /// # } + /// + /// ``` + /// + /// If the task does not have a return value, the join handle has type `JoinHandle<()>`: + /// + /// ``` + /// use tokio::task; + /// + /// # async fn doc() { + /// let join_handle: task::JoinHandle<()> = task::spawn(async { + /// println!("I return nothing."); + /// }); + /// # } + /// ``` + /// + /// Note that `handle.await` doesn't give you the return type directly. It is wrapped in a + /// `Result` because panics in the spawned task are caught by Tokio. The `?` operator has + /// to be double chained to extract the returned value: + /// + /// ``` + /// use tokio::task; + /// use std::io; + /// + /// #[tokio::main] + /// async fn main() -> io::Result<()> { + /// let join_handle: task::JoinHandle<Result<i32, io::Error>> = tokio::spawn(async { + /// Ok(5 + 3) + /// }); + /// + /// let result = join_handle.await??; + /// assert_eq!(result, 8); + /// Ok(()) + /// } + /// ``` + /// + /// If the task panics, the error is a [`JoinError`] that contains the panic: + /// + /// ``` + /// use tokio::task; + /// use std::io; + /// use std::panic; + /// + /// #[tokio::main] + /// async fn main() -> io::Result<()> { + /// let join_handle: task::JoinHandle<Result<i32, io::Error>> = tokio::spawn(async { + /// panic!("boom"); + /// }); + /// + /// let err = join_handle.await.unwrap_err(); + /// assert!(err.is_panic()); + /// Ok(()) + /// } + /// + /// ``` /// Child being detached and outliving its parent: /// /// ```no_run @@ -75,6 +140,7 @@ doc_rt_core! { /// [`task::spawn`]: crate::task::spawn() /// [`task::spawn_blocking`]: crate::task::spawn_blocking /// [`std::thread::JoinHandle`]: std::thread::JoinHandle + /// [`JoinError`]: crate::task::JoinError pub struct JoinHandle<T> { raw: Option<RawTask>, _p: PhantomData<T>, |