|
131 | 131 | //!
|
132 | 132 | //! # Examples
|
133 | 133 | //!
|
134 |
| -//! Spawn a task and block the current thread on its result: |
| 134 | +//! All examples require the [`"attributes"` feature](#features) to be enabled. |
| 135 | +//! This feature is not enabled by default because it significantly impacts |
| 136 | +//! compile times. See [`task::block_on`] for an alternative way to start |
| 137 | +//! executing tasks. |
135 | 138 | //!
|
| 139 | +//! Call an async function from the main function: |
| 140 | +//! |
| 141 | +//! ``` |
| 142 | +//! async fn say_hello() { |
| 143 | +//! println!("Hello, world!"); |
| 144 | +//! } |
| 145 | +//! |
| 146 | +//! #[async_std::main] |
| 147 | +//! async fn main() { |
| 148 | +//! say_hello().await; |
| 149 | +//! } |
| 150 | +//! ``` |
| 151 | +//! |
| 152 | +//! Await two futures concurrently, and return a tuple of their output: |
| 153 | +//! |
| 154 | +//! ``` |
| 155 | +//! #[async_std::main] |
| 156 | +//! async fn main() { |
| 157 | +//! let a = || async move { 1u8 }; |
| 158 | +//! let b = || async move { 2u8 }; |
| 159 | +//! assert_eq!(a.join(b).await, (1u8, 2u8)) |
| 160 | +//! } |
136 | 161 | //! ```
|
137 |
| -//! use async_std::task; |
138 | 162 | //!
|
139 |
| -//! fn main() { |
140 |
| -//! task::block_on(async { |
141 |
| -//! println!("Hello, world!"); |
142 |
| -//! }) |
| 163 | +//! Create a UDP server that echoes back each received message to the sender: |
| 164 | +//! |
| 165 | +//! ```no_run |
| 166 | +//! use async_std::net::UdpSocket; |
| 167 | +//! |
| 168 | +//! #[async_std::main] |
| 169 | +//! async fn main() -> std::io::Result<()> { |
| 170 | +//! let mut socket = UdpSocket::bind("127.0.0.1:8080")?; |
| 171 | +//! println!("Listening on {}", socket.local_addr()?); |
| 172 | +//! |
| 173 | +//! let mut buf = vec![0u8; 1024]; |
| 174 | +//! |
| 175 | +//! loop { |
| 176 | +//! let (recv, peer) = socket.recv_from(&mut buf).await?; |
| 177 | +//! let sent = socket.send_to(&buf[..recv], &peer).await?; |
| 178 | +//! println!("Sent {} out of {} bytes to {}", sent, recv, peer); |
| 179 | +//! } |
143 | 180 | //! }
|
144 | 181 | //! ```
|
| 182 | +//! [`task::block_on`]: task/fn.block_on.html |
145 | 183 | //!
|
146 | 184 | //! # Features
|
147 | 185 | //!
|
|
0 commit comments