Search

260629_1656_tokio+println!+format!+add

02_spawn_tasks.rs
examples

src/main.rs

async fn greet(name: &str) { println!("Hello, {}!", name); } async fn add(a: i32, b: i32) -> i32 { a + b } async fn fetch_message(id: u32) -> String { // Simulate I/O with a short delay instead of real network I/O tokio::time::sleep(std::time::Duration::from_millis(10)).await; format!("message #{}", id) } #[tokio::main] async fn main() { println!("=== async/await basics ===\n"); // Await async functions with .await greet("Tokio").await; greet("Rust").await; let sum = add(10, 32).await; println!("10 + 32 = {}", sum); // Run multiple async calls sequentially println!("\n-- sequential await --"); for id in 1..=6 { let msg = fetch_message(id).await; println!(" {}", msg); } println!("\nasync fn returns a Future."); println!("The Future does not run until you .await it."); }
Rust
복사

Cargo.toml

[package] name = "tokio_example" version = "0.1.0" edition = "2021" [dependencies] bytes = "1" futures-util = { version = "0.3", default-features = false, features = ["sink"] } tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "sync", "net", "io-util", "fs", "process", "signal"] } tokio-util = { version = "0.7", features = ["codec", "rt"] }
TOML
복사

Output

async@awaits-MacBook-Air 260629_1608_rs % cargo run Compiling tokio_example v0.1.0 (/Users/async/glory/Study/260629_1608_rs) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.16s Running `target/debug/tokio_example` === async/await basics === Hello, Tokio! Hello, Rust! 10 + 32 = 42 -- sequential await -- message #1 message #2 message #3 message #4 message #5 message #6 async fn returns a Future. The Future does not run until you .await it. async@awaits
TOML
복사

안녕하세요

관련 기술 문의와 R&D 공동 연구 사업 관련 문의는 “glory@keti.re.kr”로 연락 부탁드립니다.

Hello

For technical and business inquiries, please contact me at “glory@keti.re.kr”