async
/await
๊ฒ์์ ๋ณด์์ ๋, ๋น๋๊ธฐ Rust ์ฝ๋๋ ์ผ๋ฐ์ ์ธ ์ ์ฐจ์ ์ฝ๋์ ๋งค์ฐ ์ ์ฌํฉ๋๋ค.
use futures::executor::block_on; async fn count_to(count: i32) { for i in 1..=count { println!("์: {i}๊ฐ!"); } } async fn async_main(count: i32) { count_to(count).await; } fn main() { block_on(async_main(10)); }
ํค ํฌ์ธํธ:
-
Rust ๋น๋๊ธฐ ๋ฌธ๋ฒ์ ๋ณด์ฌ์ฃผ๋ ๊ฐ๋จํ ์์์ ๋๋ค. ์ฌ๊ธฐ์๋ ์ค๋ ์คํ๋๋ ์์ ์ด๋, ์ค์ ๋ก ๋์์ ์ํ๋๋ ๊ฒ๋ค์ ์์ต๋๋ค.
-
async
ํจ์์ ๋ฆฌํด ํ์ ์ ๋ฌด์์ธ๊ฐ์?main
์์ `let future: () = async_main(10);์ ์ฌ์ฉํ์ฌ ํ์ ์ ํ์ธํ์ธ์.
-
The โasyncโ keyword is syntactic sugar. The compiler replaces the return type with a future.
-
main
์ ๋น๋๊ธฐ ํจ์๋ก ๋ง๋ค์๋ ์์ต๋๋ค. ๋ง์ฝ ๊ทธ๋ ๊ฒ ํ ๊ฒฝ์ฐ ์ปดํ์ผ๋ฌ๋ ๋ฆฌํด ํ์ ์ธ future๋ฅผ ์ด๋ป๊ฒ ์ฌ์ฉํ ์ง ๋ชจ๋ฅด๊ธฐ ๋๋ฌธ์ ๋๋ค. -
You need an executor to run async code.
block_on
blocks the current thread until the provided future has run to completion. -
.await
๋ ๋ค๋ฅธ ์์ ์ด ์๋ฃ๋ ๋๊น์ง ๋น๋๊ธฐ์ ์ผ๋ก ๋๊ธฐํฉ๋๋ค.block_on
๊ณผ ๋ฌ๋ฆฌ.await
๋ ํ์ฌ ์ค๋ ๋๋ฅผ ๋ธ๋กํ์ง ์์ต๋๋ค. -
.await
can only be used inside anasync
function (or block; these are introduced later).