Rust to JavaScript Cheat Sheet

A quick reference for translating common Rust features to JavaScript.

Async/Await

Rust

use reqwest;
use tokio;

async fn fetch_data() -> Result<(), reqwest::Error> {
    let response = reqwest::get("https://example.com").await?;
    let data = response.text().await?;
    println!("{}", data);
    Ok(())
}

JavaScript

async function fetchData() {
    let data = await fetch("https://example.com");
    return data.json();
}

String Interpolation

Rust

let name = "Alice";
println!("Hello, {}!", name);

JavaScript

let name = "Alice";
console.log(`Hello, ${name}!`);

Objects vs Structs

Rust

struct Person {
    name: String,
    age: u8,
}

let person = Person { name: "Alice".to_string(), age: 25 };
println!("{}", person.name);

JavaScript

const person = { name: "Alice", age: 25 };
console.log(person.name);

Iterating Over an Array

Rust

let nums = vec![1, 2, 3];
for n in &nums {
    println!("{}", n);
}

JavaScript

const nums = [1, 2, 3];
nums.forEach(n => console.log(n));

Map and Filter

Rust

let nums = vec![1, 2, 3];
let squared: Vec<i32> = nums.iter().map(|&n| n * n).collect();

JavaScript

const nums = [1, 2, 3];
const squared = nums.map(n => n * n);

Handling Optional Values (null/undefined vs Option)

Rust

fn find_user(id: u32) -> Option<String> {
    if id == 1 {
        Some("Alice".to_string())
    } else {
        None
    }
}

JavaScript

function findUser(id) {
    return id === 1 ? { name: "Alice" } : null;
}

Error Handling (try/catch vs Result)

Rust

fn may_fail() -> Result<(), String> {
    Err("Something went wrong".to_string())
}

match may_fail() {
    Ok(_) => println!("Success"),
    Err(e) => println!("{}", e),
}

JavaScript

try {
    throw new Error("Something went wrong");
} catch (error) {
    console.log(error.message);
}

Parsing JSON

Rust

use serde_json::Value;

let json_str = r#"{"name": "Alice"}"#;
let obj: Value = serde_json::from_str(json_str).unwrap();
println!("{}", obj["name"]);

JavaScript

const obj = JSON.parse('{"name": "Alice"}');
console.log(obj.name);

Promises vs Futures (Delays)

Rust

use tokio::time::{sleep, Duration};

async fn delay() {
    sleep(Duration::from_millis(1000)).await;
}

JavaScript

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
await delay(1000);

Function Closures

Rust

let add = |x| move |y| x + y;
println!("{}", add(2)(3));

JavaScript

const add = (x) => (y) => x + y;
console.log(add(2)(3));

This cheat sheet covers common Rust patterns and their JavaScript equivalents.

Comments

Popular posts from this blog

Adobe® Flex® Combobox: Selecting an Item Without Using SelectedIndex

Parameters Sent by TinyWebDB in App Inventor for Android

Tic Tac Toe - Using App Inventor Beta