Module 0 · Orientation & tooling
0.1Why Rust, and the mental model shift
How a Rust program runs compared with a managed runtime, what the compiler checks before anything runs, and when Rust is the right tool.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| What you ship | JavaScript, run by Node (V8 engine, JIT compiler, garbage collector) | IL in assemblies, run by the .NET runtime (CLR, JIT compiler, garbage collector) | One native executable; no VM, no JIT, no garbage collector |
| When code becomes machine code | While the program runs, by V8's JIT | While the program runs, by the JIT (or at publish time with Native AOT) | At build time, by rustc and LLVM |
| Who frees memory | The garbage collector, some time after nothing references the object | The garbage collector, some time after nothing references the object | The compiler inserts the cleanup where the owning variable goes out of scope |
| A reference that outlives its data | Can't happen; the GC keeps the data alive | Can't happen; the GC keeps the data alive | Compile error E0597 |
| Two threads changing one variable | Not possible with ordinary objects: workers don't share them | Compiles; you must remember to lock | Compile error, unless the data is wrapped in something thread-safe such as Mutex |
TypeScriptC# runs on a managed runtime (Node and its V8 enginethe .NET runtime): a virtual machine that compiles your code while it runs and a garbage collector that frees memory behind you. Rust has neither. The compiler turns your program into a native executable ahead of time and works out, before the program ever runs, where every value is freed. This lesson shows what that changes for you, what the compiler checks in exchange, and when that trade is worth it.
A runtime and a binary
Here’s the same small program in TypeScriptC# and in Rust. Apart from syntax, it looks familiar: a function, a loop, a typed list and some string formatting.
function total(prices: number[]): number {
let sum = 0;
for (const price of prices) {
sum += price;
}
return sum;
}
const prices = [12, 30, 8];
console.log(`Total: ${total(prices)}`);int[] prices = [12, 30, 8];
Console.WriteLine($"Total: {Total(prices)}");
static int Total(int[] prices)
{
var sum = 0;
foreach (var price in prices)
{
sum += price;
}
return sum;
}fn total(prices: &[i32]) -> i32 {
let mut sum = 0;
for price in prices {
sum += price;
}
sum
}
fn main() {
let prices = [12, 30, 8];
println!("Total: {}", total(&prices));
}Output
Total: 50
A few things in the Rust version will look new. fn main is the entry point; TypeScript simply runs the file’s top-level code; C# generates one for you from top-level statements. let mut marks a variable you’re allowed to change. &[i32] means the function borrows a list of 32-bit integers instead of taking it over. The last line of total has no semicolon, so its value is what the function returns. And println! ends in ! because it’s a macro, not a function. Each of these gets its own lesson in Modules 1 to 3.
The bigger difference is what happens when you build and run it:
-
TypeScript:
tscchecks the types, then throws them away and emits JavaScript. Node’s V8 engine parses that JavaScript, interprets it, compiles the hot parts to machine code while it runs, and runs a garbage collector alongside your code.C#: the compiler emits IL (intermediate language). The .NET runtime compiles IL to machine code with its JIT as methods are first called, and runs a garbage collector. Native AOT compiles ahead of time instead, but the executable still contains the .NET runtime and its garbage collector. - Rust:
rustcchecks the types and ownership, then compiles everything to machine code through LLVM. The result is one executable. There’s no VM, no JIT warm-up and no garbage collector, and the machine running it doesn’t need Rust installed.
# TypeScript: compile, then run on Node
tsc total.ts && node total.js
# Rust: build an optimized native executable, then run it directly
cargo build --release
./target/release/total
# C#: build and run on the .NET runtime
dotnet run
# Rust: build an optimized native executable, then run it directly
cargo build --release
./target/release/total
The next lesson covers Cargo, Rust’s build tool, in detail.
Memory safety without a garbage collector
A garbage collector frees an object some time after nothing references it any more. That’s safe: you can never use memory that’s been freed. But you don’t control when it happens, the collector needs CPU time and spare memory to work, and anything that isn’t memory (a file, a socket, a database connection) still needs you to clean it up by hand.
Rust frees each value at a known point: when the variable that owns it goes out of scope. The compiler inserts that cleanup for you, for memory and for everything else. Here a Connection type announces when it’s closed:
class Connection {
readonly name: string;
constructor(name: string) {
this.name = name;
}
close(): void {
console.log(`close ${this.name}`);
}
}
const db = new Connection("db");
try {
console.log(`query ${db.name}`);
} finally {
db.close();
}
console.log("done");using (var db = new Connection("db"))
{
Console.WriteLine($"query {db.Name}");
}
Console.WriteLine("done");
sealed class Connection(string name) : IDisposable
{
public string Name { get; } = name;
public void Dispose() => Console.WriteLine($"close {Name}");
}struct Connection {
name: String,
}
impl Drop for Connection {
fn drop(&mut self) {
println!("close {}", self.name);
}
}
fn main() {
{
let db = Connection {
name: String::from("db"),
};
println!("query {}", db.name);
} // `db` goes out of scope: Rust calls drop here
println!("done");
}Output
query db close db done
In TypeScript you write try/finally. Forget it and close never runs: the garbage collector frees the object’s memory but never calls close, so the connection stays open.In C# you write using. Forget it and Dispose never runs: the garbage collector frees the object’s memory but doesn’t call Dispose, so the connection stays open (unless the type also has a finalizer, which runs whenever the collector gets round to it). In Rust there’s nothing to forget: when db goes out of scope, the compiler has already inserted a call to its drop, followed by freeing its memory. Drop is covered in Module 11; for now, notice that cleanup is automatic and happens at a point you can see in the code.
Freeing memory at a fixed point only works if nothing can still be using it afterwards. That’s the compiler’s job. Here name_ref borrows name, but name is freed at the inner closing brace, before name_ref is printed:
let name_ref;
{
let name = String::from("Ada");
name_ref = &name;
}
println!("{name_ref}");Rust doesn't compile this: error E0597
error[E0597]: `name` does not live long enough
--> main.rs:4:16
|
3 | let name = String::from("Ada");
| ---- binding `name` declared here
4 | name_ref = &name;
| ^^^^^ borrowed value does not live long enough
5 | }
| - `name` dropped here while still borrowed
6 | println!("{name_ref}");
| -------- borrow later used hereLine by line, the borrow needs to last longer than the value it points at:
| Line | Code | nameowner | name_refshared borrow (&) | What happens |
|---|---|---|---|---|
| 1 | let name_ref; | |||
| 2 | { | |||
| 3 | let name = String::from("Ada"); | ownsname starts | name owns the String | |
| 4 | name_ref = &name; | name alive | &name_ref starts | errorname does not live long enough |
| 5 | } | name ends | name_ref alive | name is dropped here while still borrowed |
| 6 | println!("{name_ref}"); | name_ref ends | the borrow is still used here |
name owns the String from line 3 and is dropped at the closing brace on line 5. name_ref borrows name on line 4 and is still used on line 6, so its bar runs past the end of name's bar. The compiler reports E0597 at the borrow on line 4: name does not live long enough.
In TypeScriptC#, the garbage collector would keep the string alive as long as something points at it. Rust has no collector, so it rejects the program instead. The checks that make this work are ownership (Module 2) and borrowing (Module 3).
Mental model shiftThe compiler does the garbage collector's job
In TypeScriptC#, the runtime decides when memory is freed, so you never think about it. In Rust, the compiler decides at build time, and it refuses programs where that decision would be unsafe. You trade some compile errors for programs with no collector, no collection pauses and predictable memory use.
Zero-cost abstractions
“Zero-cost” means high-level code compiles to roughly what you’d write by hand, so you don’t pay at run time for using it. Iterator chains are the classic example:
const scores = [3, 8, 5, 10];
const total = scores
.filter((score) => score > 4)
.map((score) => score * 2)
.reduce((sum, score) => sum + score, 0);
console.log(total);int[] scores = [3, 8, 5, 10];
var total = scores
.Where(score => score > 4)
.Select(score => score * 2)
.Sum();
Console.WriteLine(total);let scores = [3, 8, 5, 10];
let total: i32 = scores
.into_iter()
.filter(|score| *score > 4)
.map(|score| score * 2)
.sum();
println!("{total}");Output
46
Both read the same. What runs is different:
-
TypeScript:
filterandmapeach build a whole new array, and every step calls a closure.C#: LINQ is lazy, so there are no intermediate arrays, but each step is an enumerator object on the heap and each element goes through delegate calls. The JIT can optimize some of this away, but not reliably. - Rust: iterators are plain structs, and the closures are inlined into them at compile time. In a release build, the whole chain usually compiles to the same single loop you’d write by hand, with no heap allocation.
The same idea runs through the language. Generic functions are compiled separately for each concrete type they’re used with, so calls can be inlined. TypeScript works the other way round: it erases generics, so one JavaScript function handles every type.C# does this for value types; Rust does it for every type, so there’s no boxing. Module 10 covers iterators and Module 9 covers generics.
Fearless concurrency
In C#, nothing stops two threads changing the same variable at once. This compiles, runs, and usually prints a number smaller than 100000, because increments from different threads overwrite each other:
var count = 0;
Parallel.For(0, 100_000, _ => count++);
Console.WriteLine(count); // usually less than 100000TypeScript avoids data races by not sharing: worker threads don’t share ordinary objects at all, so they pass messages instead (or use SharedArrayBuffer with Atomics). In languages where threads do share memory, nothing stops two threads changing the same variable at once, and increments from different threads overwrite each other.
Rust lets threads share memory, but the compiler checks how. Four threads incrementing one counter, the classic race, doesn’t compile, because each thread would hold a mutable borrow of count at the same time:
let mut count = 0;
std::thread::scope(|s| {
for _ in 0..4 {
s.spawn(|| count += 1);
}
});
println!("{count}");Rust doesn't compile this: error E0499
error[E0499]: cannot borrow `count` as mutable more than once at a time
--> main.rs:4:17
|
2 | std::thread::scope(|s| {
| - has type `&'1 Scope<'1, '_>`
3 | for _ in 0..4 {
4 | s.spawn(|| count += 1);
| --------^^------------
| | | |
| | | borrows occur due to use of `count` in closure
| | `count` was mutably borrowed here in the previous iteration of the loop
| argument requires that `count` is borrowed for `'1`
|
note: requirement that the value outlives `'1` introduced hereTo share it, you put the counter inside a Mutex. The data lives inside the lock, so there’s no way to reach it without locking first:
use std::sync::Mutex;
let count = Mutex::new(0);
std::thread::scope(|s| {
for _ in 0..4 {
s.spawn(|| *count.lock().unwrap() += 1);
}
});
println!("{}", count.into_inner().unwrap());In C#, lock is a convention: the compiler doesn’t know which data it protects, so forgetting it is a bug you find in production.In languages where threads share memory freely, a lock is a convention: the compiler doesn’t know which data it protects, so forgetting it is a bug you find in production. In Rust, the lock is a type the compiler checks. That’s what “fearless concurrency” means: in safe Rust, data races are compile errors. (Deadlocks and other logic bugs are still possible.) Module 12 covers threads, Send and Sync.
Caught at compile timeData races
A data race is two threads accessing the same memory at once, with at least one of them writing. In C# it compiles and fails some of the time at run time, which makes it hard to reproduce.In TypeScript it can only happen through SharedArrayBuffer, and there, as in any language with shared memory, it compiles and fails only some of the time at run time, which makes it hard to reproduce. In Rust, code that could race doesn’t compile.
Which one should I use?
Rust isn’t the best choice for every project. Its checks cost you learning time and compile time, and TypeScriptC# is excellent at what it’s built for. Choose by what the project needs:
| What | When | Why | How |
|---|---|---|---|
| TypeScriptC# | Web front ends, Node services and scripts, anything that must run in the browser. Teams that already know JavaScript.Business applications, web APIs, desktop apps, games with Unity, enterprise systems. | One language for browser and server, the fastest edit-run loop, and the largest package ecosystem.A mature runtime and tooling, a large standard library, and good performance. The garbage collector handles memory for you, and that’s fine for most servers. | Node, Deno or Bun; npm for packages.dotnet new; NuGet for packages. |
| Rust | Command-line tools, latency-sensitive services, systems and embedded code, WebAssembly, and libraries that other languages call. | Predictable speed and memory use with no GC pauses, fast startup, one executable with no runtime to install, and memory and data-race bugs caught at compile time. | cargo new; crates.io for packages. The next lesson sets it up. |
| Rust inside a TypeScriptC# app | One hot path is too slow or too memory-hungry, and the rest of the app is fine. | You keep your existing code and team, and move only the part that needs it. | WebAssembly or a native Node module.A C-compatible library called with P/Invoke. Module 13 covers FFI and WebAssembly. |
Rule of thumb: if GC pauses, memory use, startup time and shipping a single binary don’t matter for your project, TypeScriptC# will usually get you there faster. Reach for Rust when they do matter, or when a bug that slips through (a memory error, a data race) would be expensive. Don’t expect Rust to be automatically faster: a slow algorithm is slow in every language, and well-written C# is often close.
Under the hood
A Rust executable contains your code, the parts of the standard library you use, and a small amount of startup code. There’s no interpreter, no JIT and no collector thread. Memory looks different too. In V8.NET, every heap object starts with a header the runtime needs: type information and bookkeeping for the garbage collector. A Rust Vec<i32> is three numbers on the stack and the bare integers on the heap:
let mut prices = vec![12, 30];
prices.push(8);
println!("{}", prices.len());The push didn’t fit in the original two slots, so the vector moved its integers to a bigger buffer with room to grow, much as a JavaScript arrayList<T> does. Today’s standard library doubles the capacity here, from 2 to 4, but the exact growth rule is an implementation detail, not a guarantee. When prices goes out of scope, the compiler has already placed a call that frees that buffer. The cost of memory management is paid in small, predictable steps at points you can see in the source, rather than by a collector that runs when it decides to.
Common pitfalls
Common pitfallDebug builds are slow
cargo run and cargo build make unoptimized debug builds so they compile quickly. They can be many times slower than release builds. Before you compare Rust’s speed with anything, build with cargo build --release or run with cargo run --release.
Common pitfallMemory safe doesn't mean leak-free
Safe Rust rules out use-after-free, double frees and data races. It doesn’t promise that every value is freed: two reference-counted values that point at each other can leak, as they would with naive reference counting anywhere. Leaks are rare in practice, and Module 11 shows how to avoid them.
Common pitfallExpect the compiler to say no
In your first weeks, many programs that would run fine in TypeScriptC# won’t compile. That’s the compiler checking things your old runtime handled for you, not a sign you’re doing it wrong. Read the whole error: it usually says what’s wrong, where, and how to fix it. The next lesson shows how to read one.
Try it yourself
Exercise: port this to Rust
Port this program to Rust. Write a count_warm function that takes the temperatures and returns how many are above 20.
function countWarm(temps: number[]): number {
let count = 0;
for (const temp of temps) {
if (temp > 20) {
count += 1;
}
}
return count;
}
const temps = [18, 23, 25, 19, 21];
console.log(`${countWarm(temps)} warm days`);int[] temps = [18, 23, 25, 19, 21];
Console.WriteLine($"{CountWarm(temps)} warm days");
static int CountWarm(int[] temps)
{
var count = 0;
foreach (var temp in temps)
{
if (temp > 20)
{
count += 1;
}
}
return count;
}Expected output
3 warm days
Show a hint
Write fn count_warm(temps: &[i32]) -> usize. Keep a let mut counter, loop with for temp in temps, and return the counter as the last line without a semicolon.
Show a solution
fn count_warm(temps: &[i32]) -> usize {
let mut count = 0;
for temp in temps {
if *temp > 20 {
count += 1;
}
}
count
}
fn main() {
let temps = [18, 23, 25, 19, 21];
println!("{} warm days", count_warm(&temps));
}The function borrows the array, counts in a mutable local and returns it as its final expression. temp is a reference to each element, so *temp reads the number itself; Module 1 explains the * symbol. Once you've met iterators you could write temps.iter().filter(|temp| **temp > 20).count() instead.
Saved in this browser only.