`Async and the Future` : How it changes the coding style in Rust

UknOwWho_Ab1r
4 min readAug 19, 2024
Ideogram.ai

As Rust developers, we’ve all been there — stuck in a sea of callbacks, struggling to keep our code organized and efficient. But what if we told you there’s a better way? A way to write code that’s not only more efficient but also more readable and maintainable. Enter the world of async and sync functions in Rust, where Futures are leading the charge.

The Problem with Sync Functions:

We’ve all written sync functions before. You know, the kind that block the execution of the next line of code until they’re done. They’re like the traffic jams of the coding world — slow, frustrating, and inefficient. But what’s the alternative?

use std::time::{Duration, Instant};
use tokio;

// Simulating a time-consuming I/O operation (e.g., network request)
fn slow_io_operation(id: u32) -> String {
std::thread::sleep(Duration::from_secs(2));
format!("Result from operation {}", id)
}

fn run_sync_operations() {
let start = Instant::now();

let result1 = slow_io_operation(1);
println!("Sync: {}", result1);

let result2 = slow_io_operation(2);
println!("Sync: {}", result2);

let result3 = slow_io_operation(3);
println!("Sync: {}", result3);

println!("Sync total time: {:?}", start.elapsed());
}

--

--