# tokio::sync::oneshot::Receiver - Rust
API documentation for the Rust `Receiver` struct in crate `tokio`.
Keywords: rust, rustlang, rust-lang, Receiver

# Struct tokio::sync::oneshot::Receiver [−] [src]

    pub struct Receiver<T> { /* fields omitted */ }

Receive a value from the associated `Sender`.

A pair of both a `Sender` and a `Receiver` are created by the `channel` function.

# Examples

    use tokio::sync::oneshot;

    #[tokio::main]
    async fn main() {
        let (tx, rx) = oneshot::channel();

        tokio::spawn(async move {
            if let Err(_) = tx.send(3) {
                println!("the receiver dropped");
            }
        });

        match rx.await {
            Ok(v) => println!("got = {:?}", v),
            Err(_) => println!("the sender dropped"),
        }
    }

If the sender is dropped without sending, the receiver will fail with `error::RecvError`:

    use tokio::sync::oneshot;

    #[tokio::main]
    async fn main() {
        let (tx, rx) = oneshot::channel::<u32>();

        tokio::spawn(async move {
            drop(tx);
        });

        match rx.await {
            Ok(_) => panic!("This doesn't happen"),
            Err(_) => println!("the sender dropped"),
        }
    }

## Implementations

### `impl<T> Receiver<T>` [src]

#### `pub fn close(&mut self)` [src]

Prevents the associated `Sender` handle from sending a value.

Any `send` operation which happens after calling `close` is guaranteed to fail. After calling `close`, `try_recv` should be called to receive a value if one was sent before the call to `close` completed.

This function is useful to perform a graceful shutdown and ensure that a value will not be sent into the channel and never received.

`close` is no-op if a message is already received or the channel is already closed.

# Examples

Prevent a value from being sent

    use tokio::sync::oneshot;
    use tokio::sync::oneshot::error::TryRecvError;

    #[tokio::main]
    async fn main() {
        let (tx, mut rx) = oneshot::channel();

        assert!(!tx.is_closed());

        rx.close();

        assert!(tx.is_closed());
        assert!(tx.send("never received").is_err());

        match rx.try_recv() {
            Err(TryRecvError::Closed) => {}
            _ => unreachable!(),
        }
    }

Receive a value sent before calling `close`

    use tokio::sync::oneshot;

    #[tokio::main]
    async fn main() {
        let (tx, mut rx) = oneshot::channel();

        assert!(tx.send("will receive").is_ok());

        rx.close();

        let msg = rx.try_recv().unwrap();
        assert_eq!(msg, "will receive");
    }

#### `pub fn try_recv(&mut self) -> Result<T, TryRecvError>` [src]

Attempts to receive a value.

If a pending value exists in the channel, it is returned. If no value has been sent, the current task will not be registered for future notification.

This function is useful to call from outside the context of an asynchronous task.

# Return

- `Ok(T)` if a value is pending in the channel.
- `Err(TryRecvError::Empty)` if no value has been sent yet.
- `Err(TryRecvError::Closed)` if the sender has dropped without sending a value.

# Examples

`try_recv` before a value is sent, then after.

    use tokio::sync::oneshot;
    use tokio::sync::oneshot::error::TryRecvError;

    #[tokio::main]
    async fn main() {
        let (tx, mut rx) = oneshot::channel();

        match rx.try_recv() {
            // The channel is currently empty
            Err(TryRecvError::Empty) => {}
            _ => unreachable!(),
        }

        // Send a value
        tx.send("hello").unwrap();

        match rx.try_recv() {
            Ok(value) => assert_eq!(value, "hello"),
            _ => unreachable!(),
        }
    }

`try_recv` when the sender dropped before sending a value

    use tokio::sync::oneshot;
    use tokio::sync::oneshot::error::TryRecvError;

    #[tokio::main]
    async fn main() {
        let (tx, mut rx) = oneshot::channel::<()>();

        drop(tx);

        match rx.try_recv() {
            // The channel will never receive a value.
            Err(TryRecvError::Closed) => {}
            _ => unreachable!(),
        }
    }

## Trait Implementations

### `impl<T: Debug> Debug for Receiver<T>` [src]

#### `fn fmt(&self, f: &mut Formatter<'_>) -> Result` [src]

Formats the value using the given formatter. Read more

### `impl<T> Drop for Receiver<T>` [src]

#### `fn drop(&mut self)` [src]

Executes the destructor for this type. Read more

### `impl<T> Future for Receiver<T>` [src]

#### `type Output = Result<T, RecvError>`

The type of value produced on completion.

#### `fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>` [src]

Attempt to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. Read more

## Auto Trait Implementations

### `impl<T> !RefUnwindSafe for Receiver<T>` [src]

### `impl<T> Send for Receiver<T> where
T: Send,` [src]

### `impl<T> Sync for Receiver<T> where
T: Send,` [src]

### `impl<T> Unpin for Receiver<T>` [src]

### `impl<T> !UnwindSafe for Receiver<T>` [src]

## Blanket Implementations

### `impl<T> Any for T where
T: 'static + ?Sized,` [src]

#### `pub fn type_id(&self) -> TypeId` [src]

Gets the `TypeId` of `self`. Read more

### `impl<T> Borrow<T> for T where
T: ?Sized,` [src]

#### `pub fn borrow(&self) -> &Tⓘ

### Notable traits for &'_ mut F

`impl<'_, F> Future for &'_ mut F where
F: Unpin + Future + ?Sized, type Output = <F as Future>::Output;`
` [src]

Immutably borrows from an owned value. Read more

### `impl<T> BorrowMut<T> for T where
T: ?Sized,` [src]

#### `pub fn borrow_mut(&mut self) -> &mut Tⓘ

### Notable traits for &'_ mut F

`impl<'_, F> Future for &'_ mut F where
F: Unpin + Future + ?Sized, type Output = <F as Future>::Output;`
` [src]

Mutably borrows from an owned value. Read more

### `impl<T> From<T> for T` [src]

#### `pub fn from(t: T) -> T` [src]

Performs the conversion.

### `impl<T, U> Into<U> for T where
U: From<T>,` [src]

#### `pub fn into(self) -> U` [src]

Performs the conversion.

### `impl<F> IntoFuture for F where
F: Future,` [src]

#### `type Output = <F as Future>::Output`

🔬 This is a nightly-only experimental API. (`into_future`)

The output that the future will produce on completion.

#### `type Future = F`

🔬 This is a nightly-only experimental API. (`into_future`)

Which kind of future are we turning this into?

#### `pub fn into_future(self) -> <F as IntoFuture>::Future` [src]

🔬 This is a nightly-only experimental API. (`into_future`)

Creates a future from a value.

### `impl<T, U> TryFrom<U> for T where
U: Into<T>,` [src]

#### `type Error = Infallible`

The type returned in the event of a conversion error.

#### `pub fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>` [src]

Performs the conversion.

### `impl<T, U> TryInto<U> for T where
U: TryFrom<T>,` [src]

#### `type Error = <U as TryFrom<T>>::Error`

The type returned in the event of a conversion error.

#### `pub fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>` [src]

Performs the conversion.