This is the full developer documentation for Rust for TS/JS Developers
# Rust for TypeScript & JavaScript Developers
> Learn Rust through side-by-side TypeScript and JavaScript comparisons covering ownership, errors, async, web APIs, databases, WebAssembly, and production.
free · open source · written for TS/JS developers
# Learn Rust from the TS/JS you know
This guide assumes you already write TypeScript or JavaScript. It uses familiar code to explain ownership, error handling, traits, async, and the Rust ecosystem, including the points where Rust needs a different approach.
$ you’ll learn ownership and borrowing
[start the guide](/00-introduction/)[why Rust?](/01-getting-started/00-why-rust/)[view the source](https://github.com/zeybek/rs4ts.dev)
// one\_problem\_two\_languages familiar control flow, explicit error types
user.ts→user.rs
typescript// familiar control flow
```ts
1
type User = { id: string; name: string };
2
3
async function getUser(id: string): Promise {
4
const response = await fetch("/api/users/" + id);
5
if (!response.ok) throw new Error("request failed");
6
return response.json();
7
}
```
rust// failure stays in the return type
```rust
1
struct User { id: String, name: String }
2
3
async fn get_user(id: &str) -> Result {
4
let url = format!("/api/users/{id}");
5
let response = reqwest::get(url).await?.error_for_status()?;
6
Ok(response.json().await?)
7
}
```
31Guide sections
6Capstone projects
2024Rust edition
MITOpen source
// how\_it\_works
## how the guide is organized
[Section titled “how the guide is organized”](#how-the-guide-is-organized)
### Start from familiar code
Chapters put familiar TS/JS code beside its Rust equivalent, then explain the rules behind the differences.
### Compare semantics, not just syntax
The guide marks places where familiar syntax behaves differently, especially around ownership, errors, async execution, and type modeling.
### Read errors with the working code
Compiler messages and common mistakes are explained beside the corrected version, so the rejected code has context.
### Practice beyond isolated snippets
Exercises reinforce individual topics. Six dependency-locked capstone crates combine them in complete programs checked by CI.
// core\_differences
## three differences to understand first
[Section titled “three differences to understand first”](#three-differences-to-understand-first)
01
### ownership\_and\_borrowing/
JavaScript relies on garbage collection. Rust uses ownership and borrowing to make data lifetime and mutation rules explicit at compile time.
\[ownership]\[borrow]\[lifetimes]\[drop]
ownership.rs
```rust
1
let s = String::from("hello");
2
let s2 = s; // ownership moves to s2
3
// println!("{s}"); // compile error: s no longer valid
4
println!("{s2}"); // ok: s2 owns the string
```
02
### result\_and\_option/
For recoverable failures, Rust returns `Result`; missing values are `Option`. The `?` operator propagates errors without hiding them from the function signature.
\[result]\[option]\[question\_mark]\[error\_types]
errors.rs
```rust
1
fn parse_double(input: &str) -> Result {
2
let n: i32 = input.trim().parse()?; // ? propagates the error
3
Ok(n * 2)
4
}
```
03
### async\_and\_concurrency/
The `async`/`await` syntax is familiar, but Rust futures are lazy and need an executor such as Tokio. Async coordinates waiting; CPU-bound parallelism is a separate choice.
\[future]\[tokio]\[tasks]\[channels]
async.rs
```rust
1
#[tokio::main]
2
async fn main() {
3
// Tokio's runtime drives both futures concurrently
4
let (a, b) = tokio::join!(fetch_user(1), fetch_user(2));
5
println!("{a:?} {b:?}");
6
}
```
// curriculum
## one guide, three stages
[Section titled “one guide, three stages”](#one-guide-three-stages)
language/00–15
Setup and syntax lead into **ownership**, collections, errors, traits, async, testing, macros, and serialization.
******
applications/ **build here**16–24
Build with **Axum**, SQLx, CLI tooling, WebAssembly, FFI, performance tools, common patterns, and the Rust ecosystem.
******
shipping/25–30
Continue with advanced topics, systems programming, **security**, production operations, migration, and the capstone projects.
******
The chapter order is the default route, not a requirement. Use the sidebar to open a topic directly when a project gives you a concrete question.
// capstone\_projects
## use Rust in complete programs
[Section titled “use Rust in complete programs”](#use-rust-in-complete-programs)
[01REST API/30-projects/00-rest-api/an Express-style CRUD service with Axum, validation, and typed errors→](/30-projects/00-rest-api/)[02CLI task manager/30-projects/01-cli-tool/subcommands, JSON persistence, file I/O, and recoverable errors→](/30-projects/01-cli-tool/)[03WebSocket chat/30-projects/03-websocket-chat/rooms, Tokio broadcast channels, shared state, and JSON messages→](/30-projects/03-websocket-chat/)[04Full-stack notes app/30-projects/05-full-stack/an Axum API and WebAssembly frontend in one Cargo workspace→](/30-projects/05-full-stack/)
The project section also includes a WASM Game of Life and a production-shaped URL shortener. [Browse all six projects →](/30-projects/)
## start with the introduction
[Section titled “start with the introduction”](#start-with-the-introduction)
It explains the intended audience, prerequisites, suggested routes, and how to use the TS/JS comparisons without treating them as exact equivalents.
[start the guide](/00-introduction/)[browse the projects](/30-projects/)
github.com/zeybek/rs4ts.dev · MIT licensed · no analytics
\>\_rs4ts
A free guide to Rust for developers who already know TypeScript or JavaScript.
[](https://github.com/zeybek/rs4ts.dev)[](https://github.com/zeybek/rs4ts.dev/stargazers)[](/llms.txt)
[start reading](/00-introduction/)[projects](/30-projects/)[migration](/29-migration-guide/)[contributing](https://github.com/zeybek/rs4ts.dev/blob/main/CONTRIBUTING.md)[license](https://github.com/zeybek/rs4ts.dev/blob/main/LICENSE)
© 2026 rs4ts.dev · MIT licensed · built by [zeybek](https://github.com/zeybek)six capstone crates are checked in CI
# Introduction
> Welcome to Rust for TS/JS Developers! This section introduces the guide and helps you get oriented.
Welcome to **Rust for TS/JS Developers**! This section introduces the guide and helps you get oriented.
***
## What’s in This Section
[Section titled “What’s in This Section”](#whats-in-this-section)
* **[Target Audience](/00-introduction/00-target-audience/)** - Who this guide is for
* **[How to Read This Guide](/00-introduction/01-how-to-read/)** - Learning strategies and navigation
* **[Prerequisites](/00-introduction/02-prerequisites/)** - What you need to know before starting
***
## About This Guide
[Section titled “About This Guide”](#about-this-guide)
This is a thorough, book-style guide designed specifically for TypeScript and JavaScript developers who want to learn Rust. Unlike general Rust tutorials, this guide:
### Leverages Your Existing Knowledge
[Section titled “Leverages Your Existing Knowledge”](#leverages-your-existing-knowledge)
We assume you already know TypeScript/JavaScript well. Instead of explaining programming from scratch, we:
* **Show familiar code first** - Start with TypeScript/JavaScript you already understand
* **Compare side-by-side** - See the Rust equivalent next to familiar code
* **Explain the differences** - Focus on what’s new, not what you already know
* **Flag gotchas** - Point out common mistakes TS/JS developers make
### Example: Variables
[Section titled “Example: Variables”](#example-variables)
Instead of just teaching Rust variables, we compare:
**TypeScript:**
```typescript
1
let x = 5; // mutable
2
const y = 10; // immutable
3
x = 6; // allowed
4
// y = 11; // error
```
**Rust:**
```rust
1
let x = 5; // immutable by default!
2
let mut y = 10; // explicitly mutable
3
// x = 6; // error - x is immutable
4
y = 11; // allowed - y is mut
```
**Key Difference:** Rust is immutable by default (opposite of JavaScript!)
***
## What You’ll Learn
[Section titled “What You’ll Learn”](#what-youll-learn)
### Core Rust Concepts
[Section titled “Core Rust Concepts”](#core-rust-concepts)
1. **The Ownership System** - Rust’s secret sauce for memory safety without garbage collection
2. **Borrowing & Lifetimes** - How Rust prevents data races at compile time
3. **Type System** - Stronger than TypeScript’s, but for good reasons
4. **Error Handling** - No exceptions, use Result and Option instead
5. **Pattern Matching** - Like switch statements on steroids
6. **Traits** - Similar to interfaces but more capable
7. **Async/Await** - Different syntax, same concepts
8. **Macros** - Compile-time code transforms (closer to Babel plugins than to decorators)
### Practical Skills
[Section titled “Practical Skills”](#practical-skills)
* Building REST APIs (Axum vs Express)
* Working with databases (SQLx, Diesel)
* Creating CLI tools (better performance than Node.js CLIs)
* WebAssembly (run Rust in the browser)
* Systems programming
* Performance optimization
* Production deployment
***
## Why Learn Rust?
[Section titled “Why Learn Rust?”](#why-learn-rust)
### For TypeScript/JavaScript Developers
[Section titled “For TypeScript/JavaScript Developers”](#for-typescriptjavascript-developers)
**You should learn Rust if you want to:**
* Build **high-performance backends** (no GC pauses; far lower p99 latency and memory use than Node.js)
* Create **CLI tools** that start instantly (no Node.js startup time)
* Eliminate **entire classes of bugs** at compile time
* Work on **systems programming** (OS, embedded, game engines)
* Add **Rust to JavaScript** via WebAssembly or native addons
* Learn a language that **makes you a better programmer**
**Rust might NOT be for you if:**
* You only build simple web frontends (stick with TypeScript)
* You need extremely fast development iteration (Node.js is faster to prototype)
* Your team isn’t ready for the learning curve
* You’re building CRUD apps where performance isn’t critical
### Real-World Use Cases
[Section titled “Real-World Use Cases”](#real-world-use-cases)
**Companies using Rust:**
* **Discord** - Rewrote its Read States service from Go to Rust, eliminating GC latency spikes
* **AWS** - Building Firecracker, Lambda runtime
* **Microsoft** - Windows components, Azure services
* **Meta** - Source control system (Sapling)
* **Cloudflare** - Edge computing platform
* **Dropbox** - File sync engine
* **npm** - Registry authorization service
**Common Rust Projects:**
* Web servers (faster than Node.js)
* CLI tools (replace Node.js CLIs)
* Game engines
* Blockchain/crypto
* Embedded systems
* Operating systems
* Database engines
* Network tools
***
## Guide Philosophy
[Section titled “Guide Philosophy”](#guide-philosophy)
### 1. Side-by-Side Comparisons
[Section titled “1. Side-by-Side Comparisons”](#1-side-by-side-comparisons)
We **always** show TypeScript/JavaScript first, then Rust. This helps you:
* Connect new concepts to existing knowledge
* Understand why Rust does things differently
* Spot patterns and differences quickly
### 2. Real-World Examples
[Section titled “2. Real-World Examples”](#2-real-world-examples)
No toy examples or contrived code. Every example:
* Uses realistic scenarios
* Includes proper error handling
* Follows best practices
* Could be used in production
### 3. Honest About Trade-offs
[Section titled “3. Honest About Trade-offs”](#3-honest-about-trade-offs)
We don’t pretend Rust is perfect. We’ll tell you:
* When Rust is harder than TypeScript
* When Node.js might be a better choice
* Where the learning curve gets steep
* How to overcome common struggles
### 4. Progressive Learning
[Section titled “4. Progressive Learning”](#4-progressive-learning)
Content is carefully sequenced:
* Foundation → Core Language → Practical Skills → Advanced Topics → Production
* Each section builds on previous ones
* Dependencies are clearly marked
* You can skip ahead, but we don’t recommend it
***
## How This Guide Is Different
[Section titled “How This Guide Is Different”](#how-this-guide-is-different)
### vs. The Rust Book
[Section titled “vs. The Rust Book”](#vs-the-rust-book)
* **The Rust Book:** Thorough, assumes no prior programming knowledge
* **This Guide:** Assumes strong TS/JS knowledge, focuses on differences
### vs. Rust by Example
[Section titled “vs. Rust by Example”](#vs-rust-by-example)
* **Rust by Example:** Brief examples with minimal explanation
* **This Guide:** Detailed explanations with side-by-side comparisons
### vs. YouTube Tutorials
[Section titled “vs. YouTube Tutorials”](#vs-youtube-tutorials)
* **YouTube:** Sequential watching, hard to reference
* **This Guide:** Written format, easy to search, return to, and reference
### vs. Rustlings
[Section titled “vs. Rustlings”](#vs-rustlings)
* **Rustlings:** Small exercises to learn by doing
* **This Guide:** Full explanations + exercises
**Best approach:** Use this guide as your primary resource, supplement with The Rust Book and Rustlings for practice.
***
## The Journey Ahead
[Section titled “The Journey Ahead”](#the-journey-ahead)
The guide moves through four phases: **Foundation** (sections 00-05, where ownership lives — take your time here), **Core Language** (06-10: data structures, collections, error handling, traits — you’ll start feeling productive), **Practical Skills** (11-19: web APIs, CLI tools, WASM — where Rust becomes fun), and **Advanced Topics** (20-30: production readiness and complete projects).
Time estimates and suggested reading paths live in [How to Read This Guide](/00-introduction/01-how-to-read/).
***
## Overcoming the Learning Curve
[Section titled “Overcoming the Learning Curve”](#overcoming-the-learning-curve)
### Common Struggles
[Section titled “Common Struggles”](#common-struggles)
**Week 1:** “Why won’t the compiler let me do this simple thing?”
* Normal! The borrow checker is strict
* Your code is probably not wrong, just needs restructuring
* This teaches you to write better code
**Week 2-3:** “I’m fighting with lifetimes!”
* Also normal! Lifetimes are the hardest part
* Most code doesn’t need explicit lifetime annotations
* It gets easier with practice
**Week 4+:** “Oh, I get it now!”
* The “aha!” moment
* Everything starts to make sense
* You begin appreciating Rust’s design
### Tips for Success
[Section titled “Tips for Success”](#tips-for-success)
1. **Don’t fight the compiler** - It’s trying to help you
2. **Read error messages carefully** - They’re very helpful
3. **Practice daily** - Even 30 minutes helps
4. **Join the community** - Discord, Reddit, forums
5. **Build projects** - Theory only goes so far
6. **Be patient** - Everyone struggles at first
7. **Celebrate small wins** - You’re learning a hard language!
***
## Next Steps
[Section titled “Next Steps”](#next-steps)
Ready to begin? Here’s your roadmap:
1. **You’re here!** - Introduction
2. **[Target Audience](/00-introduction/00-target-audience/)** - Make sure this guide is right for you
3. **[How to Read](/00-introduction/01-how-to-read/)** - Learn navigation strategies
4. **[Prerequisites](/00-introduction/02-prerequisites/)** - Verify you’re ready
5. **[Section 01: Getting Started](/01-getting-started/)** - Install Rust and write your first program!
***
## Questions?
[Section titled “Questions?”](#questions)
* **“Should I learn Rust or Go?”** - Different use cases. Rust for systems/performance, Go for simplicity/concurrency
* **“Will this replace JavaScript?”** - No, different domains. But you might build backends in Rust
* **“How long until I’m productive?”** - 3-4 weeks for basic projects, 2-3 months for production code
* **“Is Rust dying?”** - No! It has topped Stack Overflow’s “most loved/admired language” ranking every year since 2016
* **“Should I learn Rust in 2026?”** - Yes! Adoption is growing, especially in backend/systems
***
## Let’s Begin!
[Section titled “Let’s Begin!”](#lets-begin)
You’re about to learn one of the most capable programming languages in existence. It will be challenging, but rewarding.
### [Continue to Target Audience](/00-introduction/00-target-audience/)
[Section titled “Continue to Target Audience”](#continue-to-target-audience)
# Target Audience
> This guide is designed specifically for TypeScript and JavaScript developers who want to learn Rust. Let's make sure this is the right resource for you!
This guide is designed specifically for TypeScript and JavaScript developers who want to learn Rust. Let’s make sure this is the right resource for you!
***
## This Guide Is Perfect For You If…
[Section titled “This Guide Is Perfect For You If…”](#this-guide-is-perfect-for-you-if)
### You’re a TypeScript/JavaScript Developer
[Section titled “You’re a TypeScript/JavaScript Developer”](#youre-a-typescriptjavascript-developer)
* You have **1+ years** of TypeScript or JavaScript experience
* You understand **async/await, promises, and callbacks**
* You’ve worked with **npm/yarn** and modern JavaScript tooling
* You’re comfortable with **types, interfaces, and generics** (TypeScript)
* You’ve built **real applications** (not just tutorials)
### You Want to Learn Rust
[Section titled “You Want to Learn Rust”](#you-want-to-learn-rust)
* You’re curious about **systems programming**
* You want to build **high-performance backends**
* You’re interested in **WebAssembly**
* You need to create **fast CLI tools**
* You want to understand **memory management** without garbage collection
* You’re looking for a **“JavaScript alternative”** for certain use cases
### Your Learning Style
[Section titled “Your Learning Style”](#your-learning-style)
* You learn best by **comparing to what you know**
* You appreciate **detailed explanations**
* You want **production-ready examples**, not toy code
* You’re willing to invest **time to learn properly**
* You prefer **written documentation** over video tutorials
***
## This Guide Might Not Be Ideal If…
[Section titled “This Guide Might Not Be Ideal If…”](#this-guide-might-not-be-ideal-if)
### Your Background
[Section titled “Your Background”](#your-background)
* You have **less than 1 year** of programming experience
* **Better choice:** Start with [The Rust Book](https://doc.rust-lang.org/book/) which assumes no prior knowledge
* You’re **not familiar with TypeScript** or modern JavaScript (ES6+)
* **Better choice:** Learn TypeScript first, then come back
* You primarily use **vanilla JavaScript** and avoid types
* **Note:** You can still use this guide, but TypeScript knowledge helps
### Your Goals
[Section titled “Your Goals”](#your-goals)
* You only want to build **simple web frontends**
* **Stick with:** TypeScript/JavaScript - they’re perfect for that
* You need to **ship something quickly** (this week/month)
* **Better choice:** Use Node.js for now, learn Rust later
* You’re looking for an **“easy” language**
* **Reality:** Rust is challenging, but worth it
### Time Commitment
[Section titled “Time Commitment”](#time-commitment)
* You can only spare **1-2 hours total**
* **Reality:** Rust requires 20+ hours minimum to be useful
* You want to be **productive immediately**
* **Reality:** Expect 3-4 weeks before comfortable productivity
***
## Which Sections Matter Most for You?
[Section titled “Which Sections Matter Most for You?”](#which-sections-matter-most-for-you)
Different backgrounds, different priorities. Find yourself in this table:
| You are… | Why Rust fits | Start with |
| ------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------ |
| **Backend developer** (Node/Express/NestJS) hitting performance limits or cloud costs | No GC pauses, lower memory, compile-time safety | 16 (Web APIs), 17 (Database), 28 (Production) |
| **Full-stack developer** (React/Next.js) expanding your toolkit | WebAssembly, fast CLI tools, lower-level understanding | 19 (WASM), 18 (CLI Tools) |
| **Platform engineer** whose Bash/Python tooling is getting complex | Single static binary, no runtime deps, robust error handling | 18 (CLI), 24 (Tooling), 26 (Systems) |
| **Career switcher** eyeing systems/blockchain/gamedev roles | Growing demand, future-proof skill | The complete path, in order |
| **Performance optimizer** fighting Lambda cold starts and p99 latency | Predictable performance, small binaries, low latency | 16 (Web APIs), 21 (Performance), 28 (Production) |
***
## Skill Level Guide
[Section titled “Skill Level Guide”](#skill-level-guide)
### Beginner Level (This Guide Starts Here)
[Section titled “Beginner Level (This Guide Starts Here)”](#beginner-level-this-guide-starts-here)
**Your TypeScript/JavaScript Skills:**
* Can write functions, classes, async code
* Understand types, interfaces, generics
* Built at least one real application
* Comfortable with npm and modern tools
**Your Rust Skills:**
* None required!
* Never written Rust before? Perfect!
* Tried Rust but struggled? This will help!
**After This Guide:**
* Comfortable writing Rust code
* Can build web APIs, CLI tools
* Understand ownership and lifetimes
* Ready for real Rust projects
***
### Advanced Scenarios
[Section titled “Advanced Scenarios”](#advanced-scenarios)
**You’re a Rust beginner but want to learn from TS/JS perspective:**
* Perfect! This guide is designed for you
**You know some Rust but from other languages (C++, Java):**
* This guide works, but comparisons are TS/JS focused
* Still useful for different perspectives
**You’re a Rust expert looking to teach TS/JS developers:**
* Great! This guide shows you how to explain Rust concepts
***
## Not Sure If This Is For You?
[Section titled “Not Sure If This Is For You?”](#not-sure-if-this-is-for-you)
### Try This Quick Assessment
[Section titled “Try This Quick Assessment”](#try-this-quick-assessment)
**Answer these questions:**
1. Can you explain what `async/await` does in TypeScript?
2. Have you used generics (`Array`, `Promise`) in TypeScript?
3. Can you explain how `strictNullChecks` changes the way you handle `null`/`undefined`?
4. Have you built something with Express, Next.js, or similar?
5. Are you willing to spend 20+ hours learning Rust basics?
**Scoring:**
* **5 Yes:** Perfect! You’re exactly who this guide is for
* **4 Yes:** Great! You’ll do fine, might need to review TS concepts
* **3 Yes:** Okay, but consider strengthening TypeScript first
* **<3 Yes:** Build a TypeScript project first, then come back
***
## Alternative Resources
[Section titled “Alternative Resources”](#alternative-resources)
If this guide isn’t quite right, try these:
### Complete Beginners to Programming
[Section titled “Complete Beginners to Programming”](#complete-beginners-to-programming)
* **[The Rust Book](https://doc.rust-lang.org/book/)** - No prior experience needed
* **[Rustlings](https://github.com/rust-lang/rustlings)** - Learn by small exercises
### Coming from Other Languages
[Section titled “Coming from Other Languages”](#coming-from-other-languages)
* **[Rust for C++ Programmers](https://github.com/nrc/r4cppp)** - If you know C++
* **[Rust for Java Developers](https://github.com/Dhghomon/programming_rust_for_java_devs)** - If you know Java
### Prefer Video Content
[Section titled “Prefer Video Content”](#prefer-video-content)
* **[Let’s Get Rusty](https://www.youtube.com/c/LetsGetRusty)** - Video tutorials
* **[Rust Programming Course](https://www.udemy.com/course/rust-lang/)** - Udemy course
### Just Want to Experiment
[Section titled “Just Want to Experiment”](#just-want-to-experiment)
* **[Rust Playground](https://play.rust-lang.org/)** - Try Rust in browser
* **[Tour of Rust](https://tourofrust.com/)** - Interactive tutorial
***
## Still Here? Let’s Go!
[Section titled “Still Here? Let’s Go!”](#still-here-lets-go)
If you’ve made it this far, you’re probably in the right place! Here’s what to do next:
1. **You’ve confirmed this guide is for you**
2. **Next: [How to Read This Guide](/00-introduction/01-how-to-read/)** - Learn navigation strategies
3. **Then: [Prerequisites](/00-introduction/02-prerequisites/)** - Make sure you’re ready
4. **Finally: [Section 01](/01-getting-started/)** - Start learning!
***
## Still Have Questions?
[Section titled “Still Have Questions?”](#still-have-questions)
Common questions from TypeScript/JavaScript developers:
**Q: “I only know vanilla JavaScript, not TypeScript. Can I still use this?”**\
A: Yes, but it’ll be harder. Many examples use TypeScript syntax. Consider learning TypeScript basics first.
**Q: “I’m a React developer. Is Rust relevant to me?”**\
A: For React only? Not really. But for WebAssembly, CLI tools, or backend work? Absolutely!
**Q: “Will this make me abandon JavaScript?”**\
A: No! You’ll use both. Rust for performance-critical backend/systems work, TypeScript for everything else.
**Q: “Is Rust harder than TypeScript?”**\
A: Yes, significantly. But this guide makes it easier by relating to what you know.
**Q: “How much TypeScript do I need to know?”**\
A: Basic types, interfaces, generics, async/await. If you’ve shipped a TypeScript app, you’re good.
# How to Read This Guide
> This guide contains 31 sections and hundreds of pages. Here's how to navigate it effectively and get the most out of your learning experience.
This guide contains 31 sections and hundreds of pages. Here’s how to navigate it effectively and get the most out of your learning experience.
***
## Navigation Strategies
[Section titled “Navigation Strategies”](#navigation-strategies)
### Strategy 1: Sequential (Recommended for Most)
[Section titled “Strategy 1: Sequential (Recommended for Most)”](#strategy-1-sequential-recommended-for-most)
**Best for:** Beginners, those with time to learn properly
**Path:** Read sections 00-30 in order
```plaintext
1
00 → 01 → 02 → 03 → 04 → 05 → ... → 30
```
**Pros:**
* Build strong foundation
* No missing context
* Everything makes sense
**Cons:**
* Takes roughly 300-400 hours with the projects and exercises
* Slower to “useful” code
**Timeline:** About 30-40 weeks at 10 hours/week
***
### Strategy 2: Fast Track (Essentials Only)
[Section titled “Strategy 2: Fast Track (Essentials Only)”](#strategy-2-fast-track-essentials-only)
**Best for:** Experienced developers, those needing quick results
**Path:** Core sections only
```plaintext
1
00 → 01 → 02 → 03 → 04 → 05 → 08 → 11 → 16
```
Chapter 05 (Ownership) is mandatory on this route; the later chapters assume its model.
**Focus on:**
* 01: Getting Started
* 02: Basics
* 03: Functions
* 04: Control Flow
* **05: Ownership** (Don’t skip!)
* 08: Error Handling
* 11: Async
* 16: Web APIs
**Pros:**
* Focused route through the essentials (roughly 70-85 hours with practice)
* Learn by building
**Cons:**
* Missing depth
* Will need to revisit topics
**Timeline:** About 7-9 weeks at 10 hours/week
The time ranges in this page are derived from the chapter-level reading, practice, and exercise estimates. Treat them as planning ranges rather than deadlines.
***
### Strategy 3: Project-First (Learn by Doing)
[Section titled “Strategy 3: Project-First (Learn by Doing)”](#strategy-3-project-first-learn-by-doing)
**Best for:** Hands-on learners, those who hate theory
**Path:** Jump to projects, backtrack when stuck
```plaintext
1
00 → 01 → 30 (Pick a project)
2
↓
3
Get stuck → Read relevant section
4
↓
5
Continue project
```
**Flow:**
1. Read sections 00-01 (basics)
2. Jump to section 30 (projects)
3. Pick a project (REST API, CLI tool, etc.)
4. Try to build it
5. When you don’t understand something, read that section
6. Return to project
**Pros:**
* Immediately practical
* High motivation
* Learn what you need, when you need it
**Cons:**
* Can be frustrating
* Might develop bad habits
* More time overall (lots of backtracking)
**Timeline:** 4-6 weeks at 10-15 hours/week
***
### Strategy 4: Domain-Specific
[Section titled “Strategy 4: Domain-Specific”](#strategy-4-domain-specific)
**Best for:** Those with specific goals (web dev, CLI, etc.)
#### For Web API Developers
[Section titled “For Web API Developers”](#for-web-api-developers)
```plaintext
1
00 → 01 → 02 → 05 → 06 → 08 → 11 → 12 → 15 → 16 → 17 → 27 → 28
2
↑ ↑ └─→ Database
3
Basics Ownership Security & Production
```
#### For CLI Tool Developers
[Section titled “For CLI Tool Developers”](#for-cli-tool-developers)
```plaintext
1
00 → 01 → 02 → 05 → 06 → 07 → 08 → 12 → 13 → 18 → 24
2
Basics Own. Data Collections CLI Testing Tooling
```
#### For Systems Programmers
[Section titled “For Systems Programmers”](#for-systems-programmers)
```plaintext
1
00 → 01 → 02 → 05 → 10 → 20 → 21 → 26
2
Basics Own. Smart Unsafe Perf Systems
3
Ptr.
```
#### For WebAssembly Developers
[Section titled “For WebAssembly Developers”](#for-webassembly-developers)
```plaintext
1
00 → 01 → 02 → 05 → 06 → 12 → 15 → 19
2
Basics Own. Data Mods Serde WASM
```
***
## How Each Section Is Organized
[Section titled “How Each Section Is Organized”](#how-each-section-is-organized)
### Section Structure
[Section titled “Section Structure”](#section-structure)
Every section follows this pattern:
```plaintext
1
XX-section-name/
2
├── index.md # Section overview, navigation
3
├── 00-topic-1.md # Individual topics
4
├── 01-topic-2.md
5
└── ...
```
### Topic File Structure
[Section titled “Topic File Structure”](#topic-file-structure)
Each **concept topic** includes the parts below. (Orientation pages like this one, and the capstone projects in Section 30, use a tailored subset. For example, projects end with “Extending It” instead of graded exercises.)
1. **Quick Overview** - 2-3 sentence summary
2. **TypeScript/JavaScript Example** - Code you know
3. **Rust Equivalent** - The Rust way
4. **Detailed Explanation** - How and why
5. **Key Differences** - Important changes from TS/JS
6. **Common Pitfalls** - What TS/JS devs get wrong
7. **Best Practices** - Idiomatic Rust
8. **Real-World Example** - Production code
9. **Further Reading** - Additional resources
10. **Exercises** - Practice problems
***
## How to Approach Each Topic
[Section titled “How to Approach Each Topic”](#how-to-approach-each-topic)
### Step 1: Read the Overview
[Section titled “Step 1: Read the Overview”](#step-1-read-the-overview)
Understand what you’re about to learn and why it matters.
### Step 2: Study the TypeScript Example
[Section titled “Step 2: Study the TypeScript Example”](#step-2-study-the-typescript-example)
This should be familiar. If it’s not, review TypeScript first.
### Step 3: Compare to Rust
[Section titled “Step 3: Compare to Rust”](#step-3-compare-to-rust)
Look for similarities and differences. Don’t just read the Rust code: compare it line by line to the TypeScript.
### Step 4: Read the Explanation
[Section titled “Step 4: Read the Explanation”](#step-4-read-the-explanation)
Understand not just “how” but “why” Rust does it this way.
### Step 5: Note the Pitfalls
[Section titled “Step 5: Note the Pitfalls”](#step-5-note-the-pitfalls)
These are real mistakes TS/JS developers make. Avoid them!
### Step 6: Try It Yourself
[Section titled “Step 6: Try It Yourself”](#step-6-try-it-yourself)
```bash
1
# Create a playground
2
cargo new try_this
3
cd try_this
4
5
# Edit src/main.rs
6
# Try the examples yourself!
7
cargo run
```
### Step 7: Do the Exercises
[Section titled “Step 7: Do the Exercises”](#step-7-do-the-exercises)
If provided, complete the exercises. They reinforce learning.
***
## Time Management
[Section titled “Time Management”](#time-management)
### Daily Learning (30-60 minutes)
[Section titled “Daily Learning (30-60 minutes)”](#daily-learning-30-60-minutes)
**Best for:** Busy professionals
```plaintext
1
Day 1: Read one topic (30 min)
2
Day 2: Try examples, exercises (30 min)
3
Day 3: Read next topic (30 min)
4
Day 4: Review and practice (30 min)
5
Day 5: Build something small (1 hour)
6
Weekend: Longer project work
```
**Progress:** Complete guide in 2-3 months
### Weekend Warrior (5-10 hours/week)
[Section titled “Weekend Warrior (5-10 hours/week)”](#weekend-warrior-5-10-hoursweek)
**Best for:** Those with weekday commitments
```plaintext
1
Saturday: 3-4 hours learning
2
Sunday: 2-3 hours practicing
3
Weekdays: Quick reviews (15 min/day)
```
**Progress:** Complete guide in 1.5-2 months
### Intensive (20+ hours/week)
[Section titled “Intensive (20+ hours/week)”](#intensive-20-hoursweek)
**Best for:** Bootcamp style, career transition
```plaintext
1
Morning: 2-3 hours reading/learning
2
Afternoon: 2-3 hours practicing
3
Evening: 1-2 hours review/projects
```
**Progress:** Complete guide in 3-4 weeks
***
## Reading Tips
[Section titled “Reading Tips”](#reading-tips)
### Active Reading
[Section titled “Active Reading”](#active-reading)
**Don’t just read - engage!**
**Bad:** Skim through, think “that makes sense” **Good:** Type every example, modify it, break it, fix it
**Bad:** Read code once, move on **Good:** Read it 3 times - once for syntax, once for meaning, once for patterns
**Bad:** Skip exercises **Good:** Do all exercises, even if they seem easy
### Taking Notes
[Section titled “Taking Notes”](#taking-notes)
**Create a Rust learning journal:**
```markdown
1
# Day 1: Variables and Mutability
2
3
## Key Insight
4
5
Rust is immutable by default! Opposite of JS.
6
7
## Syntax I Need to Remember
8
9
let x = 5; // immutable
10
let mut y = 5; // mutable
11
12
## Gotcha
13
14
Forgot `mut` and spent 10 minutes debugging why
15
assignment failed. Compiler error was helpful though!
16
17
## Try Tomorrow
18
19
Practice with loops and mutable counters
```
### When You’re Stuck
[Section titled “When You’re Stuck”](#when-youre-stuck)
**Follow this process:**
1. **Read the error message** - Rust errors are helpful!
2. **Check the relevant section** - Find the topic
3. **Try the Rust Playground** - Isolate the problem
4. **Ask for help** - Discord, Reddit, Stack Overflow
5. **Take a break** - Sometimes you just need to sleep on it
***
## Bookmark These
[Section titled “Bookmark These”](#bookmark-these)
Keep these sections handy for quick reference:
### Essential References
[Section titled “Essential References”](#essential-references)
* **[05 - Ownership](/05-ownership/)** - You’ll refer back constantly
* **[07 - Collections](/07-collections/)** - String and Vec APIs
* **[08 - Error Handling](/08-error-handling/)** - Result and Option
* **[09 - Traits](/09-generics-traits/)** - Common trait patterns
### Quick Lookups
[Section titled “Quick Lookups”](#quick-lookups)
* **[02 - Basics](/02-basics/)** - Type conversion, operators
* **[12 - Modules](/12-modules-packages/)** - Import syntax
* **[24 - Tooling](/24-tooling/)** - Cargo commands
***
## Study Aids
[Section titled “Study Aids”](#study-aids)
### Cheat Sheets (Create Your Own!)
[Section titled “Cheat Sheets (Create Your Own!)”](#cheat-sheets-create-your-own)
**TypeScript → Rust Quick Reference:**
```typescript
1
// TypeScript
2
const x = 5;
3
let y = [1, 2, 3];
4
async function f() { ... }
5
interface User { name: string }
```
```rust
1
// Rust
2
let x = 5;
3
let mut y = vec![1, 2, 3];
4
async fn f() { ... }
5
struct User { name: String }
```
### Flashcards
[Section titled “Flashcards”](#flashcards)
Use Anki, Quizlet, or paper cards for:
* Syntax conversions
* Ownership rules
* Common patterns
* Error types
### Practice Projects
[Section titled “Practice Projects”](#practice-projects)
After each major section, build something:
* **After 05:** Simple CLI calculator
* **After 08:** Error-handling file reader
* **After 11:** Async HTTP client
* **After 16:** Basic REST API
* **After 30:** Your own project!
***
## Learning with Others
[Section titled “Learning with Others”](#learning-with-others)
### Study Groups
[Section titled “Study Groups”](#study-groups)
Find or create a study group:
* Discord channels
* Local meetups
* Online cohorts
* Pair programming
**Benefits:**
* Stay motivated
* Learn from others’ questions
* Teach to reinforce learning
* Make friends in Rust community
### Code Review
[Section titled “Code Review”](#code-review)
Share your code:
* Reddit r/rust (helpful community!)
* Discord #beginners channel
* GitHub discussions
* Stack Overflow
***
## Track Your Progress
[Section titled “Track Your Progress”](#track-your-progress)
### Section Checklist
[Section titled “Section Checklist”](#section-checklist)
Keep track of what you’ve completed:
```plaintext
1
[ ] 00 - Introduction
2
[ ] 01 - Getting Started
3
[ ] 02 - Basics
4
...
5
[ ] 30 - Projects
```
### Skill Assessment
[Section titled “Skill Assessment”](#skill-assessment)
Periodically check yourself:
**Week 1:**
* Can I create a new Cargo project?
* Do I understand mutable vs immutable?
* Have I written a basic function?
**Week 2:**
* Do I understand ownership?
* Can I use borrowing correctly?
* Have I successfully used Vec and String?
**Week 4:**
* Can I handle errors with Result?
* Do I understand traits?
* Have I written async code?
**Week 8:**
* Can I build a REST API?
* Do I understand lifetimes?
* Have I shipped a Rust project?
***
## Goal Setting
[Section titled “Goal Setting”](#goal-setting)
### Set Clear Milestones
[Section titled “Set Clear Milestones”](#set-clear-milestones)
**Bad goal:** “Learn Rust”\
**Good goal:** “Build a REST API that handles user authentication by end of month”
**Bad goal:** “Understand ownership”\
**Good goal:** “Complete section 05 and build a CLI tool that manipulates strings without compiler errors”
### Celebrate Wins
[Section titled “Celebrate Wins”](#celebrate-wins)
Learning Rust is hard! Celebrate progress:
* First successful compile
* First program without compiler errors
* Understanding ownership
* First async program
* First production code
* Helping another beginner
***
## What NOT to Do
[Section titled “What NOT to Do”](#what-not-to-do)
### Common Mistakes
[Section titled “Common Mistakes”](#common-mistakes)
**Skipping Section 05 (Ownership)** → You’ll be confused forever. Don’t skip it!
**Rushing through examples** → Type them out, don’t just read
**Comparing to JavaScript too much** → Rust is different. Embrace it!
**Fighting the compiler** → It’s helping you. Listen to it!
**Learning in isolation** → Join the community, ask questions
**Giving up after Day 3** → Week 1 is the hardest. Push through!
**Trying to memorize everything** → Focus on understanding, reference docs for details
***
## After Completing This Guide
[Section titled “After Completing This Guide”](#after-completing-this-guide)
### What’s Next?
[Section titled “What’s Next?”](#whats-next)
1. **Build a real project** - Not a tutorial, something you’ll use
2. **Contribute to open source** - Find a Rust project
3. **Read advanced resources** - [Rust for Rustaceans](https://rust-for-rustaceans.com/)
4. **Keep practicing** - Skills decay without use
5. **Teach others** - Best way to solidify knowledge
### Staying Current
[Section titled “Staying Current”](#staying-current)
Rust evolves. Stay updated:
* [This Week in Rust](https://this-week-in-rust.org/)
* [Rust Blog](https://blog.rust-lang.org/)
* [Reddit r/rust](https://reddit.com/r/rust)
* [Rust Discord](https://discord.gg/rust-lang)
***
## Getting Help
[Section titled “Getting Help”](#getting-help)
### When You’re Stuck
[Section titled “When You’re Stuck”](#when-youre-stuck-1)
**Good question template:**
```plaintext
1
I'm trying to [specific goal].
2
3
I expected [what you thought would happen].
4
5
Instead, [what actually happened].
6
7
Here's my code: [minimal example]
8
9
Error message: [full error]
10
11
I've tried: [what you've attempted]
```
### Where to Ask
[Section titled “Where to Ask”](#where-to-ask)
* **Beginners:** [Discord #beginners](https://discord.gg/rust-lang)
* **Code review:** [r/rust](https://reddit.com/r/rust)
* **Specific errors:** Stack Overflow
* **General discussion:** [Rust Users Forum](https://users.rust-lang.org/)
***
## You’re Ready!
[Section titled “You’re Ready!”](#youre-ready)
You now know how to navigate this guide effectively. Choose your strategy and let’s begin!
### Your Next Steps
[Section titled “Your Next Steps”](#your-next-steps)
1. **You know how to use this guide**
2. **Next: [Prerequisites](/00-introduction/02-prerequisites/)** - Verify you’re ready
3. **Then: [Section 01](/01-getting-started/)** - Start coding!
# Prerequisites
> Before you start Rust, let's make sure you have the necessary background knowledge and tools. This will set you up for a smooth learning experience.
Before you start Rust, let’s make sure you have the necessary background knowledge and tools. This will set you up for a smooth learning experience.
***
## Required Knowledge
[Section titled “Required Knowledge”](#required-knowledge)
### 1. TypeScript/JavaScript Experience (Required)
[Section titled “1. TypeScript/JavaScript Experience (Required)”](#1-typescriptjavascript-experience-required)
You should be comfortable with:
#### Basic Programming
[Section titled “Basic Programming”](#basic-programming)
```typescript
1
// Variables and types
2
let name: string = "Alice";
3
const age: number = 30;
4
let isActive: boolean = true;
5
6
// Functions
7
function greet(name: string): string {
8
return `Hello, ${name}!`;
9
}
10
11
// Arrow functions
12
const add = (a: number, b: number): number => a + b;
```
**Why it matters:** These map directly to Rust concepts. If this looks unfamiliar, review JavaScript/TypeScript basics first.
#### Arrays and Objects
[Section titled “Arrays and Objects”](#arrays-and-objects)
```typescript
1
// Arrays
2
const numbers: number[] = [1, 2, 3, 4, 5];
3
const doubled = numbers.map((n) => n * 2);
4
const filtered = numbers.filter((n) => n > 2);
5
6
// Objects and interfaces
7
interface User {
8
id: number;
9
name: string;
10
email: string;
11
}
12
13
const user: User = {
14
id: 1,
15
name: "Alice",
16
email: "alice@example.com",
17
};
```
**Why it matters:** Collections work similarly in Rust (Vec, HashMap, etc.)
#### Async/Await
[Section titled “Async/Await”](#asyncawait)
```typescript
1
// Promises and async/await
2
async function fetchUser(id: number): Promise {
3
const response = await fetch(`/api/users/${id}`);
4
const data = await response.json();
5
return data;
6
}
7
8
// Error handling
9
try {
10
const user = await fetchUser(1);
11
console.log(user);
12
} catch (error) {
13
console.error("Failed:", error);
14
}
```
**Why it matters:** Rust has async/await too, with similar (but not identical) syntax.
#### Generics
[Section titled “Generics”](#generics)
```typescript
1
// Generic functions
2
function first(arr: T[]): T | undefined {
3
return arr[0];
4
}
5
6
// Generic interfaces
7
interface Response {
8
data: T;
9
status: number;
10
}
11
12
const userResponse: Response = {
13
data: user,
14
status: 200,
15
};
```
**Why it matters:** Rust’s generics are similar but can do more.
#### Modules and Imports
[Section titled “Modules and Imports”](#modules-and-imports)
```typescript
1
// Importing
2
import { User, fetchUser } from "./api";
3
import type { Config } from "./config";
4
5
// Exporting
6
export interface Product {
7
id: number;
8
name: string;
9
}
10
11
export function getProducts(): Product[] {
12
// ...
13
}
```
**Why it matters:** Rust’s module system is similar conceptually.
***
### 2. Command Line Basics (Required)
[Section titled “2. Command Line Basics (Required)”](#2-command-line-basics-required)
You should know how to:
```bash
1
# Navigate directories
2
cd ~/projects
3
ls
4
pwd
5
6
# Create files and directories
7
mkdir my-project
8
touch file.txt
9
10
# Run commands
11
node app.js
12
npm install
13
npm start
14
15
# View file contents
16
cat README.md
17
18
# Basic git
19
git clone
20
git add .
21
git commit -m "message"
```
**Why it matters:** You’ll use terminal commands for Cargo and rustc.
***
### 3. Development Tools (Required)
[Section titled “3. Development Tools (Required)”](#3-development-tools-required)
#### Text Editor/IDE
[Section titled “Text Editor/IDE”](#text-editoride)
You need a text editor. Recommended options:
**VS Code** (Most popular)
```bash
1
# Install VS Code
2
# Then install rust-analyzer extension
3
code --install-extension rust-lang.rust-analyzer
```
**Other options:**
* **IntelliJ IDEA** with Rust plugin
* **Vim/Neovim** with rust.vim
* **Emacs** with rust-mode
* **Sublime Text** with Rust Enhanced
**Why it matters:** You’ll write lots of Rust code!
#### Terminal/Shell
[Section titled “Terminal/Shell”](#terminalshell)
* macOS/Linux: Built-in terminal
* Windows: PowerShell, WSL2, or Git Bash
***
## Helpful but Not Required
[Section titled “Helpful but Not Required”](#helpful-but-not-required)
### Nice to Have
[Section titled “Nice to Have”](#nice-to-have)
#### System Programming Concepts
[Section titled “System Programming Concepts”](#system-programming-concepts)
If you’ve heard of these, great! If not, don’t worry, we’ll explain:
* **Stack vs Heap** - We’ll teach you
* **Pointers** - Rust handles them safely
* **Memory management** - Rust’s ownership system makes it easier
* **Compilation** - You’ll learn as you go
#### Other Compiled Languages
[Section titled “Other Compiled Languages”](#other-compiled-languages)
Experience with these helps but isn’t necessary:
* C, C++, Go, Java, C#, Swift, Kotlin
**If you have:** Great! Some concepts will feel familiar\
**If you don’t:** Perfect! You’ll learn Rust’s way without bad habits
***
## What You DON’T Need
[Section titled “What You DON’T Need”](#what-you-dont-need)
### You Don’t Need to Know
[Section titled “You Don’t Need to Know”](#you-dont-need-to-know)
**Computer Science degree** - Nope! **Low-level programming** - We’ll teach you **C or C++** - Actually better if you don’t (fewer preconceptions) **Assembly** - Not at all **Operating systems** - Helpful but not required **Math** - Just basic programming logic
### You Don’t Need to Be
[Section titled “You Don’t Need to Be”](#you-dont-need-to-be)
**A “10x developer”** - Everyone starts somewhere **A CS major** - Self-taught? Perfect! **Young** - Age doesn’t matter **A native English speaker** - Code is universal
***
## System Requirements
[Section titled “System Requirements”](#system-requirements)
### Operating System
[Section titled “Operating System”](#operating-system)
Rust works on:
* **Linux** (any distro)
* **macOS** (10.7+)
* **Windows** (7+, but 10+ recommended)
* **BSD, etc.**
**Note for Windows users:** Consider using [WSL2](https://docs.microsoft.com/en-us/windows/wsl/install) for a better experience. Or use PowerShell/CMD - both work fine.
### Hardware
[Section titled “Hardware”](#hardware)
**Minimum:**
* 2 GB RAM (4 GB recommended)
* 2 GB disk space
* Any processor from the last 10 years
**Why it matters:** Rust compilation can be slow on old hardware.
### Internet Connection
[Section titled “Internet Connection”](#internet-connection)
Required for:
* Installing Rust
* Downloading dependencies (crates)
* Accessing documentation
**Tip:** Once you’ve downloaded crates, you can work offline.
***
## Required Software
[Section titled “Required Software”](#required-software)
### 1. Node.js (for TypeScript examples)
[Section titled “1. Node.js (for TypeScript examples)”](#1-nodejs-for-typescript-examples)
```bash
1
# Check if installed
2
node --version # Should be 22+ (any maintained LTS works)
3
npm --version # Comes bundled with Node
4
5
# If not installed: https://nodejs.org/
```
**Why:** We’ll compare TypeScript and Rust code side-by-side.
### 2. TypeScript (optional but recommended)
[Section titled “2. TypeScript (optional but recommended)”](#2-typescript-optional-but-recommended)
```bash
1
# Install globally
2
npm install -g typescript
3
4
# Verify
5
tsc --version
```
**Why:** To run the TypeScript examples in this guide.
### 3. Git (recommended)
[Section titled “3. Git (recommended)”](#3-git-recommended)
```bash
1
# Check if installed
2
git --version
3
4
# If not installed: https://git-scm.com/
```
**Why:** For cloning examples and managing your code.
***
## Pre-Learning Checklist
[Section titled “Pre-Learning Checklist”](#pre-learning-checklist)
Before starting Section 01, verify:
### Knowledge Checklist
[Section titled “Knowledge Checklist”](#knowledge-checklist)
* [ ] I can write TypeScript functions with type annotations
* [ ] I understand async/await and Promises
* [ ] I’ve used generics (`Array`, `Promise`)
* [ ] I know basic terminal commands (cd, ls, mkdir)
* [ ] I’ve built at least one TypeScript/JavaScript application
### Tools Checklist
[Section titled “Tools Checklist”](#tools-checklist)
* [ ] I have a text editor/IDE installed
* [ ] I can open and use a terminal
* [ ] I have Node.js installed (node —version works)
* [ ] I have Git installed (optional but recommended)
* [ ] I have at least 2 GB free disk space
### Mindset Checklist
[Section titled “Mindset Checklist”](#mindset-checklist)
* [ ] I’m ready to invest 20+ hours learning
* [ ] I’m okay with compiler errors (they’re helpful!)
* [ ] I’m willing to think differently about programming
***
## Quick Self-Assessment
[Section titled “Quick Self-Assessment”](#quick-self-assessment)
### Test Your TypeScript Knowledge
[Section titled “Test Your TypeScript Knowledge”](#test-your-typescript-knowledge)
Try to answer these without looking them up:
**Question 1:**
```typescript
1
const numbers = [1, 2, 3, 4, 5];
2
const result = numbers.map((n) => n * 2).filter((n) => n > 5);
```
What is `result`?
Answer
`[6, 8, 10]` - Numbers doubled, then filtered to only values > 5
**Question 2:**
```typescript
1
interface User {
2
name: string;
3
age?: number;
4
}
```
What does the `?` mean?
Answer
Optional property - `age` may or may not be present
**Question 3:**
```typescript
1
async function fetchData(): Promise {
2
const response = await fetch("/api/data");
3
return response.text();
4
}
```
What does this function return?
Answer
A `Promise` - The function is async, so it always returns a Promise
**Scoring:**
* **3/3:** Perfect! You’re ready
* **2/3:** Good, review weak areas
* **1/3 or less:** Review TypeScript basics first
***
## Recommended Pre-Reading (Optional)
[Section titled “Recommended Pre-Reading (Optional)”](#recommended-pre-reading-optional)
If you want to prepare even more:
### For TypeScript Review
[Section titled “For TypeScript Review”](#for-typescript-review)
* [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
* [TypeScript Deep Dive](https://basarat.gitbook.io/typescript/)
### For Programming Concepts
[Section titled “For Programming Concepts”](#for-programming-concepts)
* [JavaScript.info](https://javascript.info/) - Modern JavaScript
* [MDN Web Docs](https://developer.mozilla.org/) - Web APIs
### For Command Line
[Section titled “For Command Line”](#for-command-line)
* [Command Line Crash Course](https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line)
***
## Ready to Install Rust?
[Section titled “Ready to Install Rust?”](#ready-to-install-rust)
If you’ve checked all the boxes above, you’re ready!
### What’s Next?
[Section titled “What’s Next?”](#whats-next)
1. **You’ve verified prerequisites**
2. **Next: [Section 01 - Getting Started](/01-getting-started/)**
3. **Install Rust and write your first program!**
***
## Still Not Sure?
[Section titled “Still Not Sure?”](#still-not-sure)
### Common Concerns
[Section titled “Common Concerns”](#common-concerns)
**“I’ve only used JavaScript, not TypeScript.”** → That’s okay! You’ll learn TypeScript concepts as we compare to Rust. Just note that examples use TypeScript syntax.
**“I’ve never compiled a program before.”** → Perfect! We’ll walk you through it. Compilation is just turning code into an executable.
**“The terminal scares me.”** → Don’t worry! We’ll explain every command. You’ll be comfortable with it soon.
**“I don’t have much time.”** → Start with 30 minutes a day. Progress is progress!
**“What if I get stuck?”** → Join the [Rust Discord](https://discord.gg/rust-lang) - the community is super helpful!
**“Am I too old/young/etc. to learn Rust?”** → Absolutely not! If you can write TypeScript, you can learn Rust.
***
## You’re All Set!
[Section titled “You’re All Set!”](#youre-all-set)
You have the knowledge and tools needed. Time to write some Rust!
# JavaScript & TypeScript to Rust Cheatsheet
> The fast map from JavaScript and TypeScript to Rust: variables, array methods, null handling, promises, classes, and modules, each linked to a full chapter.
A single-page lookup for the question you will ask most often while learning Rust: *“what is the Rust equivalent of this JavaScript or TypeScript thing?”* Each row pairs the code you already write on the left with its idiomatic Rust counterpart on the right. The mappings are deliberately terse; every section links to the full chapter where the *why* lives.
If you only skim one page before starting, make it this one, then keep it open in a tab.
***
## Variables and types
[Section titled “Variables and types”](#variables-and-types)
| TypeScript / JavaScript | Rust |
| ------------------------------------- | ---------------------------------------------------------------------------------------- |
| `let x = 1` (reassignable) | `let mut x = 1;` |
| `const x = 1` (no reassign) | `let x = 1;` (immutable by default) |
| `const MAX = 100` (true constant) | `const MAX: i32 = 100;` |
| reassign with a new type | shadowing: `let x = 5; let x = "five";` |
| `number` | sized: `i32`, `i64`, `u32`, `usize`, `f64` |
| `bigint` (arbitrary precision) | `i128` / `u128` (fixed 128-bit; for true arbitrary precision use the `num-bigint` crate) |
| `string` | `String` (owned) and `&str` (borrowed) |
| `boolean` | `bool` |
| `null` / `undefined` | `Option` with `None` |
| `any` | no equivalent; reach for generics, an `enum`, or `serde_json::Value` |
| `[1, 2, 3]` | `vec![1, 2, 3]` (a growable `Vec`) |
| fixed-length tuple `[string, number]` | `(String, i32)` |
| `{ id: 1 }` object | a `struct`, or a `HashMap` for dynamic keys |
See: [Variables and Mutability](/02-basics/00-variables/), [Basic Types](/02-basics/01-types/), [Stack vs Heap](/05-ownership/00-stack-heap/).
***
## Functions and closures
[Section titled “Functions and closures”](#functions-and-closures)
| TypeScript / JavaScript | Rust |
| -------------------------------------------- | -------------------------------------------------- |
| `function add(a: number, b: number): number` | `fn add(a: i32, b: i32) -> i32` |
| `return a + b;` | `a + b` (last expression, no `return`, no `;`) |
| `(x) => x + 1` | `\|x\| x + 1` |
| capturing closure `() => count++` | `move \|\| count += 1` (see `Fn`/`FnMut`/`FnOnce`) |
| default parameter `f(a = 1)` | no defaults; take `Option` or use a builder |
| rest parameter `...args` | a slice `args: &[T]` |
| `void` return | `()` (the unit type) |
| pass a function `g(f)` | `fn g(f: impl Fn() -> T)` |
See: [Basic Functions](/03-functions/00-basic-functions/), [Parameters](/03-functions/01-parameters/), [Arrow Functions vs Closures](/03-functions/03-arrow-vs-closures/), [Higher-Order Functions](/03-functions/04-higher-order/).
***
## Control flow
[Section titled “Control flow”](#control-flow)
| TypeScript / JavaScript | Rust |
| ----------------------------- | ----------------------------------------------- |
| `cond ? a : b` | `if cond { a } else { b }` (an expression) |
| `if (value)` (truthy) | `if value` (must be a real `bool`) |
| `switch (x) { ... }` | `match x { ... }` (exhaustive, no fall-through) |
| `for (let i = 0; i < n; i++)` | `for i in 0..n` |
| `for (const x of arr)` | `for x in &arr` |
| `arr.forEach(f)` | `arr.iter().for_each(f)` or a `for` loop |
| `while (cond)` | `while cond` |
| `while (true) { ... }` | `loop { ... }` (can `break value`) |
| labelled `break outer` | `'outer: loop { break 'outer; }` |
See: [Conditionals](/04-control-flow/00-conditionals/), [Match](/04-control-flow/02-match/), [Loops](/04-control-flow/01-loops/), [if let / while let](/04-control-flow/03-if-let-while-let/).
***
## Null, undefined, and errors
[Section titled “Null, undefined, and errors”](#null-undefined-and-errors)
There is no `null` and no `undefined` in Rust. Absence is the `None` variant of `Option`, and a failure is the `Err` variant of `Result`. The type system makes you handle both.
| TypeScript / JavaScript | Rust |
| --------------------------------- | ---------------------------------------------- |
| `value ?? fallback` | `option.unwrap_or(fallback)` |
| `obj?.prop` (optional chaining) | `option.map(\|o\| o.prop)` / `.and_then(...)` |
| `if (x != null) { use(x) }` | `if let Some(x) = option { use(x) }` |
| `throw new Error("boom")` | `return Err(MyError::Boom)` |
| `try { ... } catch (e) { ... }` | `match result { Ok(v) => ..., Err(e) => ... }` |
| `const v = await f()` (may throw) | `let v = f().await?;` |
| rethrow / propagate | the `?` operator |
| `class HttpError extends Error` | `enum AppError { ... }` with `thiserror` |
See: [Result and Option](/08-error-handling/00-result-option/), [The `?` Operator](/08-error-handling/01-question-mark/), [Option Enum](/06-data-structures/03-option-enum/), [Custom Errors](/08-error-handling/04-custom-errors/).
***
## Collections and array methods
[Section titled “Collections and array methods”](#collections-and-array-methods)
Most array methods exist in Rust, but on **iterators**, and they are **lazy**: nothing runs until a consumer such as `.collect()`, `.sum()`, or a `for` loop pulls the values through.
| TypeScript / JavaScript | Rust |
| ------------------------------------- | --------------------------------------------------- |
| `arr.map(f)` | `arr.iter().map(f).collect()` |
| `arr.filter(f)` | `arr.iter().filter(f).collect()` |
| `arr.reduce(f, init)` | `arr.iter().fold(init, f)` |
| `arr.find(f)` | `arr.iter().find(f)` (returns `Option`) |
| `arr.some(f)` / `arr.every(f)` | `arr.iter().any(f)` / `.all(f)` |
| `arr.includes(x)` | `arr.contains(&x)` |
| `arr.push(x)` / `arr.length` | `vec.push(x)` / `vec.len()` |
| `arr.slice(a, b)` | `&vec[a..b]` |
| `arr.sort()` | `vec.sort()` |
| `[...a, ...b]` | `a.iter().chain(&b).collect()` |
| `new Map()` / `map.get(k)` | `HashMap::new()` / `map.get(&k)` (returns `Option`) |
| `new Set()` | `HashSet::new()` |
| `Object.keys(o)` / `Object.values(o)` | `map.keys()` / `map.values()` |
| `Array.from({ length: n }, ...)` | `(0..n).map(...).collect()` |
See: [Vectors](/07-collections/00-vectors/), [Iterators](/07-collections/06-iterators/), [Iterator Consumers](/07-collections/07-iterator-consumers/), [HashMaps](/07-collections/03-hashmaps/).
***
## Strings
[Section titled “Strings”](#strings)
| TypeScript / JavaScript | Rust |
| ---------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `"hello " + name` | `format!("hello {name}")` |
| `` `total: ${n}` `` (template) | `format!("total: {n}")` |
| `s.length` (UTF-16 code units — `"🎉".length === 2`) | `s.chars().count()` (Unicode scalars) or `s.len()` (UTF-8 bytes); neither matches JS exactly |
| `s.toUpperCase()` | `s.to_uppercase()` |
| `s.split(",")` | `s.split(',')` |
| `s.includes("x")` | `s.contains("x")` |
| `s.trim()` | `s.trim()` |
| `s.replace(a, b)` | `s.replace(a, b)` |
| `s.startsWith("/")` | `s.starts_with('/')` |
| accept a string argument | take `&str`, return `String` |
See: [Strings](/07-collections/01-strings/), [String Manipulation](/07-collections/02-string-manipulation/).
***
## Structs, enums, classes, and interfaces
[Section titled “Structs, enums, classes, and interfaces”](#structs-enums-classes-and-interfaces)
Rust has no classes and no inheritance. Data lives in a `struct` or `enum`; behaviour lives in `impl` blocks; shared behaviour is a `trait` (an interface you can implement for any type).
| TypeScript / JavaScript | Rust |
| ------------------------------- | -------------------------------------------- |
| `interface User { id: number }` | `struct User { id: i32 }` |
| `class C { method() {} }` | `struct C; impl C { fn method(&self) {} }` |
| `type Shape = Circle \| Square` | `enum Shape { Circle, Square }` |
| discriminated union with data | `enum` variants carry data |
| `implements Serializable` | `impl Serializable for T` |
| `extends Base` (inheritance) | composition plus traits (no inheritance) |
| `this` | `&self`, `&mut self`, or `self` |
| `new C(args)` | `C::new(args)` (a convention, not a keyword) |
| `instanceof` | `match` on an `enum` or a trait object |
| generic `class Box` | `struct Box` with trait bounds |
See: [Structs](/06-data-structures/00-structs/), [Enums](/06-data-structures/02-enums/), [impl Blocks](/06-data-structures/05-impl-blocks/), [Traits](/09-generics-traits/03-traits/), [Trait Objects](/09-generics-traits/06-trait-objects/).
***
## Async
[Section titled “Async”](#async)
The keywords match, but Rust futures are **lazy** (they do nothing until `.await`ed) and there is no built-in event loop, so you pick a runtime such as Tokio.
| TypeScript / JavaScript | Rust |
| ------------------------------- | ----------------------------------------------------- |
| `Promise` | `impl Future