Reference
Rosetta stone
Common constructs side by side with their Rust equivalents, each linked to the lesson that explains it.
Find the thing you already write in TypeScriptC#, read across to the Rust version, and follow the link when you want the details. Cells are short on purpose: they show the usual spelling, not every option. “None” means Rust has no direct equivalent, and the cell says what to do instead.
Variables & constants
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
const total = 5;var total = 5; (no read-only locals) | let total = 5;: immutable by default | Variables |
let total = 5;var total = 5;, then total += 1; | let mut total = 5;, then total += 1; | Variables |
let n: number = 5;int n = 5; | let n: i32 = 5; | Variables |
const items = []; items.push(1); (contents still change)readonly List<int> items (contents still change) | let mut items = Vec::new();: without mut the contents can’t change either | Variables |
Redeclaring a name: compile errorRedeclaring a name: error CS0128 | Shadowing: let input = input.trim();, even with a new type | Variables |
const MAX_RETRIES = 3; at module levelconst int MaxRetries = 3; | const MAX_RETRIES: u32 = 3;: type required, copied into every use | Variables |
A module-level letA static field | static COUNT: AtomicU64 = AtomicU64::new(0);: immutable unless thread-safe | Variables |
A module-level const computed on loadstatic readonly field, or Lazy<T> | static CONFIG: LazyLock<Config> = LazyLock::new(load); | Variables |
const [a, b] = pair;var (a, b) = pair; | let (a, b) = pair; | Destructuring |
const { x, y } = point;var (x, y) = point; (deconstruction) | let Point { x, y } = point; | Destructuring |
Numbers & types
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
number (whole numbers)int | i32: the default for whole numbers | Primitive types |
number or bigintlong, ulong | i64, u64 | Primitive types |
number, or one element of a Uint8Arraybyte | u8; binary data is &[u8] or Vec<u8> | Primitive types |
number for an index or lengthint for an index or Count | usize: what len() returns and indexing takes | Primitive types |
number (64-bit float)double, float | f64, f32 | Primitive types |
No decimal typedecimal for money | None in std: integer cents in an i64, or the rust_decimal crate | Primitive types |
booleanbool | bool | Primitive types |
A one-character stringchar: one UTF-16 code unit | char: one Unicode scalar value, 4 bytes; literal 'a' | Primitive types |
0xFF, 0b1010, 1_000_000, 10n0xFF, 0b1010, 1_000_000, 10L, 1.5f | 0xFF, 0b1010, 1_000_000, 10i64, 1.5f32, b'a' | Primitive types |
No widening neededImplicit: long big = small; | Always explicit: i64::from(small) or small.into() | Primitive types |
No integer types to narrowchecked((int)big): throws if it doesn’t fit | i32::try_from(big): returns a Result | Primitive types |
n | 0: cut to 32 bits(int)big: cuts off bits | big as i32: cuts off bits on purpose | Primitive types |
Math.trunc(x)(int)x | x as i32: truncates, and saturates at the type’s limits | Primitive types |
Past 2^53, number silently loses precisionInteger overflow wraps silently (unchecked by default) | Panics in debug builds, wraps in release; checked_add, wrapping_add, saturating_add say which you want | Primitive types |
Math.abs(x), Math.sqrt(x), x ** 2Math.Abs(x), Math.Sqrt(x), Math.Pow(x, 2) | Methods: x.abs(), x.sqrt(), x.powi(2); n.pow(2) for integers | Primitive types |
Number(text): NaN if it isn’t a numberint.Parse(text) throws; int.TryParse(text, out var n) | text.parse::<i32>(): returns Result<i32, ParseIntError> | Result & ? |
Tuple [string, number]Tuple (string, int) | Tuple (&str, i32), read with .0, .1 | Primitive types |
number[] (can always grow)int[] (length not in the type) | [i32; 3]: the length is part of the type | Primitive types |
type UserId = number; (just another name)using UserId = int; (just another name) | type UserId = u64; is just another name; struct UserId(u64); is a new type | Structs |
typeof x at run timex.GetType() | None: no type information at run time; generics are compiled per type | Generics |
Strings
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
stringstring, or StringBuilder to build one | String: owned, growable, UTF-8 | Slices |
string (a parameter or a piece of one)ReadOnlySpan<char> | &str: a borrowed view of UTF-8 text | Slices |
"hello""hello" (interned) | "hello" is a &'static str; String::from("hello") or "hello".to_string() for an owned one | Slices |
`Hi ${name}`$"Hi {name}" | format!("Hi {name}") | Strings |
console.log(text)Console.WriteLine(text) | println!("{text}") | Macros |
console.log(obj)A record’s generated ToString() | println!("{obj:?}") with #[derive(Debug)]; {obj:#?} to pretty-print | Standard traits |
console.log("total", total)Debug.WriteLine(total) | dbg!(total): prints file, line, expression and value | Macros |
x.toFixed(2)$"{x:F2}" | format!("{x:.2}") | Strings |
s.length: UTF-16 code unitss.Length: UTF-16 code units | s.len(): bytes; s.chars().count(): characters | Strings |
a + b | a + &b (moves a), or format!("{a}{b}") | Strings |
s += "!"sb.Append("!") | s.push_str("!"), s.push('!'); s must be mut | Strings |
parts.join(", ")string.Join(", ", parts) | parts.join(", ") | Strings |
s.split(",")s.Split(',') | s.split(','): a lazy iterator of &str | Strings |
s.trim().split(/\s+/)s.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries) | s.split_whitespace() | Strings |
s.includes("x")s.Contains("x") | s.contains("x") | Strings |
s.startsWith("v"), s.endsWith("!")s.StartsWith("v"), s.EndsWith("!") | s.starts_with("v"), s.ends_with('!'); s.strip_prefix("v") returns Option<&str> | Strings |
s.indexOf("x"): -1 if missings.IndexOf("x"): -1 if missing | s.find("x"): Option<usize>, a byte offset | Strings |
s.replaceAll("a", "b")s.Replace("a", "b") | s.replace("a", "b"): replaces every match | Strings |
s.slice(0, 5): a copys[..5]: a copy; s.AsSpan(..5): a view | &s[..5]: a view; byte offsets, panics inside a character | Slices |
s[0]s[0] | s[0] doesn’t compile; s.chars().next() or s.as_bytes()[0] | Strings |
for (const c of s)foreach (var c in s) | for c in s.chars(); s.char_indices() for byte positions too | Strings |
a === ba == b | a == b, also between String and &str | Strings |
new TextDecoder().decode(bytes)Encoding.UTF8.GetString(bytes) | String::from_utf8(bytes): a Result; String::from_utf8_lossy(&bytes) never fails | Strings |
String.raw`C:\temp`@"C:\temp", """raw""" | r"C:\temp", r#"say "hi""# | Strings |
Override toString()Override ToString() | impl Display for T; then {} and .to_string() work | Standard traits |
Functions & closures
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
function add(a: number, b: number): numberstatic int Add(int a, int b) | fn add(a: i32, b: i32) -> i32 | Functions |
return a + b; | a + b as the last expression, with no semicolon; return for early exits | Functions |
const sq = (x: number) => x * x;int Sq(int x) => x * x; | fn sq(x: i32) -> i32 { x * x } | Functions |
void | () (unit): leave out -> | Functions |
never[DoesNotReturn] | -> ! | Functions |
| A block is a statementA block is a statement | A block is an expression: let y = { let t = f(); t * 2 }; | Functions |
function greet(name = "you"), name?: stringvoid Greet(string name = "you") | None: take an Option<T>, or write a second function | Functions |
| Overload signaturesMethod overloads | None: different names, like String::new() and String::with_capacity(10) | Functions |
function sum(...nums: number[])int Sum(params int[] nums) | None: take a slice, fn sum(nums: &[i32]); macros like println! can | Macros |
An options object: connect({ retries: 3 })Named arguments: Connect(retries: 3) | None: pass a struct, often Options { retries: 3, ..Default::default() } | Structs |
return [min, max];return (min, max); | (min, max), then let (lo, hi) = bounds(&xs); | Primitive types |
Return an objectout int value | Return a tuple, an Option or a Result | Option |
Wrap the number in an object to change itref int count, called with ref n | count: &mut i32, called with &mut n, changed with *count += 1 | References |
An inner function that uses outer variablesA local function that uses outer variables | An inner fn can’t see outer variables; use a closure | Closures |
(x) => x * 2x => x * 2 | |x| x * 2 | Closures |
(x: number): number => { … }(int x) => { … } | |x: i32| -> i32 { … } | Closures |
| Captures see the variable itselfCaptures live in a shared hidden object | Captured by &, &mut or by move, depending on what the body does | Closures |
| Captures stay alive automaticallyCaptures stay alive automatically | move |x| x + offset: the closure owns what it captures | Closures |
| A callback that changes a captured counterA lambda that changes a captured counter | let mut inc = || count += 1;: an FnMut, and inc must be mut | Closures |
rule: (n: number) => numberFunc<int, int> rule | rule: impl Fn(i32) -> i32 (a generic, the default) | Closures |
A field holding a functionA Func<int, int> field or a list of them | Box<dyn Fn(i32) -> i32> | Closures |
function adder(n: number) { return (x: number) => x + n; }Func<int, int> Adder(int n) => x => x + n; | fn adder(n: i32) -> impl Fn(i32) -> i32 { move |x| x + n } | Closures |
Control flow & matching
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
if (x > 0) { … } else { … } | if x > 0 { … } else { … }: no parentheses, braces required | Loops & conditionals |
cond ? a : b | if cond { a } else { b }: if is an expression | Loops & conditionals |
while (n > 0) { … } | while n > 0 { … } | Loops & conditionals |
while (true) { … break; } | loop { … break; } | Loops & conditionals |
A variable set before breakA variable set before break | let found = loop { break value; }; | Loops & conditionals |
for (let i = 0; i < 10; i++)for (var i = 0; i < 10; i++) | for i in 0..10 | Loops & conditionals |
for (let i = 0; i <= 10; i++)for (var i = 0; i <= 10; i++) | for i in 0..=10 | Loops & conditionals |
for (let i = 0; i < 10; i += 2)for (var i = 0; i < 10; i += 2) | for i in (0..10).step_by(2) | Lazy iterators |
for (const x of xs)foreach (var x in xs) | for x in &xs (borrow) or for x in xs (move) | Loops & conditionals |
for (const [i, x] of xs.entries())foreach (var (i, x) in xs.Index()) | for (i, x) in xs.iter().enumerate() | Loops & conditionals |
outer: label and break outer;goto or a flag variable | 'outer: for … and break 'outer; | Loops & conditionals |
switch (code) { case 1: … }code switch { 1 => "one", _ => "other" } | match code { 1 => "one", _ => "other" } | Match |
case 1: case 2: (fall-through)1 or 2 => | 1 | 2 =>; never any fall-through | Match |
if (n >= 1 && n <= 9)>= 1 and <= 9 => | 1..=9 => | Match |
An if inside the casevar n when n > 100 => | n if n > 100 => (a guard) | Match |
Missing case: compiles, unless a never check catches itMissing case: warning CS8509, then an exception | Missing case: compile error E0004 | Match |
point.x === 0point is { X: 0 } | Point { x: 0, .. } in a pattern; .. skips the other fields | Match |
const [first, ...rest] = xs;xs is [var first, .. var rest] | if let [first, rest @ ..] = xs.as_slice(); [first, .., last] | Rust’s symbols |
["a", "b"].includes(c)c is 'a' or 'b' | matches!(c, 'a' | 'b') | Match |
if (shape.kind === "circle") { … }if (shape is Circle c) { … } | if let Shape::Circle { radius } = shape { … } | if let |
if (x === undefined) return;if (x is not string s) return; | let Some(s) = x else { return; }; | if let |
while ((x = stack.pop()) !== undefined)while (stack.TryPop(out var x)) | while let Some(x) = stack.pop() | if let |
Null & errors
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
T | undefined, T | nullT? | Option<T>: Some(value) or None | Option |
undefined, nullnull | None; a present value is Some(x) | Option |
Using it unchecked: error with strictNullChecksUsing it unchecked: warning CS8602 | Compile error: an Option<T> is not a T | Option |
value ?? fallback | value.unwrap_or(fallback); unwrap_or_else(|| …) computes it lazily | Option |
user?.address?.cityuser?.Address?.City | user.and_then(|u| u.address), or ? in a function that returns Option | Option |
x === undefined ? undefined : f(x)x is null ? null : F(x) | x.map(f) | Option |
if (x !== undefined) { use(x); }if (x is { } v) { Use(v); } | if let Some(v) = x { use_it(v); } | if let |
value! (no check at run time) | value.expect("why it's there"): checks, and panics if it’s None | Option |
| A function that throws; the signature doesn’t say soA method that throws; the signature doesn’t say so | Returns Result<T, E>: Ok(value) or Err(error) | Result & ? |
throw new Error("bad input")throw new FormatException("bad input") | return Err(ParseError::BadInput); | Result & ? |
| Don’t catch; the exception keeps going upDon’t catch; the exception keeps going up | ? after the call: let n = text.parse::<i32>()?; | Result & ? |
try { … } catch (e) { … }try { … } catch (Exception e) { … } | match result { Ok(v) => …, Err(e) => … } | Result & ? |
catch that returns a fallbackcatch that returns a fallback | result.unwrap_or(0), result.unwrap_or_else(|e| …) | Result & ? |
throw new Error(message, { cause })throw new AppException(message, inner) | .map_err(|e| …)?, or ? converts with From | Result & ? |
| Missing value becomes a thrown errorNull becomes a thrown exception | opt.ok_or(MyError::Missing)?; result.ok() goes the other way | Result & ? |
class ConfigError extends Errorclass ConfigException : Exception | An enum that implements Display and std::error::Error | Custom errors |
| Exported error classes in a libraryCustom exception classes in a library | #[derive(thiserror::Error)] on an enum, with #[error("…")] per variant | Custom errors |
catch (e: unknown) and log itcatch (Exception e) and log it | anyhow::Result<T> plus .context("loading config")? in an application | Custom errors |
throw new RangeError(…) for a bugthrow new ArgumentOutOfRangeException(…) for a bug | panic!("…"), assert!(cond): the program stops | Custom errors |
Uncaught exception in the entry point: exit code 1Unhandled exception in Main: the process crashes | fn main() -> Result<(), Box<dyn Error>>: prints Error: …, exits with code 1 | Result & ? |
finally { file.close(); }finally { file.Dispose(); } | Nothing to write: Drop runs when the owner goes out of scope | Drop |
Collections & iterators
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
T[]List<T> | Vec<T> | Collections |
[1, 2, 3][1, 2, 3] (collection expression) | vec![1, 2, 3] | Collections |
[]new List<int>(capacity) | Vec::new(), Vec::with_capacity(n) | Collections |
xs.push(x)xs.Add(x) | xs.push(x); xs must be mut | Collections |
xs.pop(): undefined if emptyxs.RemoveAt(xs.Count - 1) | xs.pop(): an Option<T> | Collections |
xs = xs.filter((x) => x > 0)xs.RemoveAll(x => x <= 0) | xs.retain(|&x| x > 0): in place | Collections |
xs.lengthxs.Count | xs.len(), xs.is_empty() | Collections |
xs[i]: undefined if out of rangexs[i]: throws if out of range | xs[i] panics; xs.get(i) returns an Option | Collections |
xs[0], xs.at(-1)xs[0], xs[^1] | xs.first(), xs.last(): Options | Collections |
xs.includes(x)xs.Contains(x) | xs.contains(&x) | Collections |
xs.sort((a, b) => a - b)xs.Sort() | xs.sort(); floats: xs.sort_by(|a, b| a.total_cmp(b)) | Standard traits |
xs.sort((a, b) => a.age - b.age)xs.Sort((a, b) => a.Age.CompareTo(b.Age)) | xs.sort_by_key(|p| p.age) | Closures |
xs.slice(1, 4): a copyxs.AsSpan(1..4) on an array: a view | &xs[1..4]: a view, no copy | Slices |
Map<K, V>Dictionary<TKey, TValue> | HashMap<K, V> | Collections |
new Map([["a", 1]])new Dictionary<string, int> { ["a"] = 1 } | HashMap::from([("a", 1)]) | Collections |
m.set(k, v)d[k] = v | m.insert(k, v) | Collections |
m.get(k): undefined if missingd.TryGetValue(k, out var v) | m.get(&k): an Option<&V> | Collections |
m.has(k), m.delete(k)d.ContainsKey(k), d.Remove(k) | m.contains_key(&k), m.remove(&k) | Collections |
m.set(w, (m.get(w) ?? 0) + 1)d[w] = d.GetValueOrDefault(w) + 1; | *m.entry(w).or_insert(0) += 1; | Collections |
Map.groupBy(words, (w) => w.length)words.GroupBy(w => w.Length) | groups.entry(w.len()).or_default().push(w); in a loop | Collections |
for (const [k, v] of m)foreach (var (k, v) in d) | for (k, v) in &m; order is unspecified | Collections |
Sort the keys yourselfSortedDictionary<TKey, TValue> | BTreeMap<K, V>: always in key order | Collections |
Set<T>HashSet<T> | HashSet<T>; BTreeSet<T> for sorted | Collections |
xs.push(x) and xs.shift()Queue<T>: Enqueue, Dequeue | VecDeque<T>: push_back, pop_front | Collections |
xs.map(f): runs at oncexs.Select(f): lazy | xs.iter().map(f): lazy, runs when consumed | Lazy iterators |
xs.filter(f)xs.Where(f) | xs.iter().filter(|x| …) | Lazy iterators |
The result is already an array.ToList() | .collect::<Vec<_>>() | Lazy iterators |
xs.reduce((a, b) => a + b, 0)xs.Sum() | xs.iter().sum::<i32>() | Lazy iterators |
xs.reduce(f, init)xs.Aggregate(init, f) | xs.iter().fold(init, |acc, x| …) | Lazy iterators |
xs.find(f): undefined if nonexs.FirstOrDefault(f) | xs.iter().find(|x| …): an Option | Lazy iterators |
xs.some(f), xs.every(f)xs.Any(f), xs.All(f) | .any(|x| …), .all(|x| …) | Lazy iterators |
xs.slice(0, 3), xs.slice(3)xs.Take(3), xs.Skip(3) | .take(3), .skip(3); .take_while(…), .skip_while(…) | Lazy iterators |
xs.flatMap(f), xs.flat()xs.SelectMany(f) | .flat_map(f), .flatten() | Lazy iterators |
a.map((x, i) => [x, b[i]])a.Zip(b) | a.iter().zip(&b) | Lazy iterators |
Math.max(...xs)xs.Max(), xs.MaxBy(p => p.Age) | .max(), .max_by_key(|p| p.age): Options | Lazy iterators |
[...new Set(xs)]xs.Distinct() | .collect::<HashSet<_>>(), or xs.sort(); xs.dedup(); | Collections |
| No distinction between reading, changing and taking itemsNo distinction between reading, changing and taking items | .iter() (&T), .iter_mut() (&mut T), .into_iter() (T) | Lazy iterators |
| An iterator is empty on the second passA query runs again on every enumeration | Using a consumed iterator again: compile error E0382 | Lazy iterators |
A generator: function* with yieldIEnumerable<T> with yield return | A struct with impl Iterator: type Item and fn next | Lazy iterators |
Structs, enums & methods
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
class Point { x = 0; y = 0; }, or an interfaceclass, struct or record | struct Point { x: f64, y: f64 } | Structs |
{ x: 1, y: 2 }, new Point(1, 2)new Point(1, 2) | Point { x: 1.0, y: 2.0 }: a struct literal | Structs |
constructor(x: number, y: number)A constructor, or a primary constructor | fn new(x: f64, y: f64) -> Self by convention, called Point::new(1.0, 2.0) | Structs |
{ ...defaults, port: 8080 }defaults with { Port = 8080 } | Config { port: 8080, ..defaults }: moves the other fields | Structs |
Methods inside the classMethods inside the type | impl Point { fn len(&self) -> f64 { … } } | Structs |
this, implicitthis, implicit | self, &self or &mut self, written as the first parameter | Structs |
A method that changes thisA method that changes fields | fn add(&mut self, …); the caller’s variable must be mut | Structs |
| No equivalentNo equivalent | fn finish(self): takes ownership, so the value can’t be used afterwards | Structs |
static origin()static Point Origin() | Associated function fn origin() -> Self, called Point::origin() | Structs |
get area()public double Area => …; | No properties: a method, fn area(&self) -> f64 | Structs |
private or #fieldprivate fields | Fields are private to the module unless marked pub | Modules |
A branded typereadonly record struct UserId(int Value) | struct UserId(u64); (a newtype), read as id.0 | Structs |
Field initializersField initializers, default(T) | #[derive(Default)], then Config::default() | Standard traits |
class B extends Aclass B : A | None: put an A field inside B; share behavior with traits | Structs |
type Light = "red" | "green";enum Light { Red, Green } | enum Light { Red, Green } | Enums |
No numeric value for a string union(int)Light.Red, and (Light)42 compiles | Light::Red as i32; a value outside the list is impossible | Enums |
A discriminated union with a kind tagAn abstract record with a sealed record per case | enum Shape { Circle { r: f64 }, Rect { w: f64, h: f64 } } | Enums |
switch (shape.kind)switch expression with type patterns | match shape { Shape::Circle { r } => …, Shape::Rect { w, h } => … } | Enums |
| Functions that take the unionMethods on the base record | impl Shape { fn area(&self) -> f64 { match self { … } } } | Enums |
Nothing generatedA record generates Equals, GetHashCode and ToString | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | Standard traits |
Interfaces/traits & generics
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
interface Shape { area(): number; }interface IShape { double Area(); } | trait Shape { fn area(&self) -> f64; } | Traits |
Any matching object fits; implements Shape is optionalclass Square : IShape | impl Shape for Square { … }, a block of its own | Traits |
| An abstract base class method with a bodyA default interface method | A default method with a body in the trait; callable on the type directly | Traits |
| A plain functionAn extension method | Your own trait implemented for the type: impl Shout for str | Traits |
Not allowed in an interfacestatic abstract interface members | Associated functions in the trait: fn unit() -> Self; | Traits |
function wrap<T>(x: T): T[]List<T> Wrap<T>(T x) | fn wrap<T>(x: T) -> Vec<T> | Generics |
<T extends Shape>where T : IShape | <T: Shape> | Generics |
T extends Shape & Namedwhere T : IShape, INamed | T: Shape + Display, or where T: Shape + Display | Generics |
a >= b works on any Twhere T : IComparable<T> and CompareTo | T: PartialOrd, then a >= b | Generics |
class Pair<T>class Pair<T> | struct Pair<T> { a: T, b: T } and impl<T> Pair<T> { … } | Generics |
A this: parameter on a methodAn extension method with its own constraint | impl<T: PartialOrd> Pair<T> { … }: methods only for some T | Generics |
| Type parameters erasedReal types at run time | One compiled copy per type used (monomorphization) | Generics |
shape: ShapeIShape shape | shape: &impl Shape (static dispatch) or shape: &dyn Shape (dynamic) | impl vs. dyn |
Shape[]List<IShape> | Vec<Box<dyn Shape>> | impl vs. dyn |
Return type ShapeReturn type IShape | -> impl Shape for one concrete type; -> Box<dyn Shape> when it varies | impl vs. dyn |
| A generic parameter on the interfaceA generic parameter on the interface | An associated type: type Item;, used as Iterator<Item = u32> | Lazy iterators |
A toString() methodOverride ToString() | impl Display | Standard traits |
An equals method you writeIEquatable<T>, Equals, == | #[derive(PartialEq, Eq)], then == | Standard traits |
Objects as Map keys compare by referenceGetHashCode() that agrees with Equals | #[derive(Hash)] next to Eq | Standard traits |
A compare function passed to sortIComparable<T>, IComparer<T> | #[derive(PartialOrd, Ord)], or impl Ord | Standard traits |
Conversion functions you nameimplicit and explicit operators | impl From<A> for B, then B::from(a) or a.into(); TryFrom when it can fail | Standard traits |
No operator overloading: a plus methodpublic static Point operator +(Point a, Point b) | impl Add for Point { type Output = Point; fn add(self, o: Point) -> Point { … } } | Standard traits |
Ownership & borrowing
Most rows here have no direct equivalent in TypeScriptC#: the garbage collector handles what ownership and borrowing handle in Rust.
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
| The garbage collector frees memory laterThe garbage collector frees memory later | The owner frees it when it goes out of scope | Ownership |
The engine decides where data livesstruct or class decides, then the runtime | You decide, through the types you pick; String and Vec keep their data on the heap | Stack & heap |
const b = a; shares one arrayvar b = a; shares one List<T> | let b = a; moves it; using a afterwards is error E0382 | Ownership |
| Numbers are copiedValue types are copied | Types that implement Copy are copied: integers, floats, bool, char | Copy & Clone |
{ ...obj } or structuredClone(obj)with, or a copy constructor | .clone(): a visible, deep copy of what the value owns | Copy & Clone |
Nothing to opt intoDeclare it as a struct | #[derive(Clone, Copy)] if every field is Copy | Copy & Clone |
Pass the object; the function shares itPass the object; in for a large struct | &T: lend it to read | References |
Pass the object and change itPass the object; ref for a struct | &mut T: lend it to change | References |
| Pass the object and store itPass the object and store it | T: ownership moves in | Choosing parameter types |
| Two writers to one object: allowedTwo writers to one object: allowed | Two &mut at once: error E0499 | References |
Changing an array while looping over it: allowedChanging a list while enumerating it: InvalidOperationException | Error E0502 at compile time | References |
| No dangling references; the GC keeps data aliveNo dangling references; the GC keeps data alive | A reference that outlives its value: error E0597 | References |
| No equivalentNo equivalent | Lifetimes: fn longest<'a>(a: &'a str, b: &'a str) -> &'a str | Lifetimes |
Any field can refer to any objectA ref struct holding a Span<T> | struct Highlight<'a> { text: &'a str }: can’t outlive the text | Lifetimes |
No equivalentNo equivalent (static means a type member) | &'static str: valid for the whole program; T: 'static: holds no expiring borrow | Lifetimes |
Every object is on the heap alreadyBoxing a struct into object, implicitly | Box::new(value): one heap allocation, always explicit | Stack & heap |
| Every object can be sharedEvery class instance can be shared | Rc<T> on one thread, Arc<T> across threads; Rc::clone(&a) | Shared ownership |
| Change a shared object through any referenceChange a shared object through any reference | Rc<RefCell<T>> on one thread; Arc<Mutex<T>> across threads | Shared ownership |
| Parent and child point at each other; the GC copesParent and child point at each other; the GC copes | Child to parent with Weak<T>, or the cycle leaks | Shared ownership |
using res = … with [Symbol.dispose]()using var res = … with IDisposable | Automatic for every value; impl Drop adds your own cleanup | Drop |
Call the close method earlyCall Dispose() early | drop(value); later uses are compile errors | Drop |
Return a string either wayReturn a string either way | Cow<'a, str>: borrowed when unchanged, owned when changed | Drop & smart pointers |
Modules & packages
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
A file is a moduleA namespace, independent of files | mod cart; loads cart.rs; mod cart { … } inline | Modules |
Private to the file until exportedprivate members, internal types | Private to the module (and modules inside it) by default | Modules |
exportpublic | pub | Modules |
Left out of the package’s exports mapinternal | pub(crate) | Modules |
import { total } from "./cart.js";using Shop.Cart; | use crate::shop::cart::total; | Modules |
export { total } from "./cart.js";No equivalent | pub use cart::total; | Modules |
"../" and "./" pathsNamespaces are absolute | super:: (parent), self:: (this module), crate:: (root) | Modules |
package.json, tsconfig.jsonMyApp.csproj | Cargo.toml | Tooling |
package-lock.json, pnpm-lock.yamlpackages.lock.json (opt-in) | Cargo.lock | Tooling |
| npmjs.comnuget.org | crates.io | Tooling |
npm install zoddotnet add package Serilog | cargo add serde --features derive | Tooling |
npm install -D vitestA package in the test project | cargo add --dev …: goes under [dev-dependencies] | Crates & workspaces |
"^1.0.200"Version="1.0.200" (a minimum; restores the lowest match) | "1.0.200": any later 1.x, newest picked; "=1.0.200" pins | Tooling |
A bin entry, or main / exports<OutputType>Exe</OutputType>, or a class library | src/main.rs (binary crate) or src/lib.rs (library crate) | Crates & workspaces |
| npm or pnpm workspacesA solution with project references | A Cargo workspace: [workspace] in the root Cargo.toml | Crates & workspaces |
"billing": "workspace:*"<ProjectReference Include="../Billing/Billing.csproj" /> | billing = { path = "../billing" } | Crates & workspaces |
| Separate add-on packagesSeparate add-on packages | Cargo features: [features] and #[cfg(feature = "json")] | Crates & workspaces |
A bundler replaces process.env.NODE_ENV#if DEBUG | #[cfg(debug_assertions)], cfg!(debug_assertions) | Crates & workspaces |
Async & concurrency
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
async function load(): Promise<User>async Task<User> LoadAsync() | async fn load() -> User | Async |
await load()await LoadAsync() | load().await: postfix | Async |
| Starts when called (promises are eager)Starts when called (tasks are hot) | Starts when first awaited or polled (futures are lazy) | Async |
| The event loop is built inThe thread pool is built in | Add a runtime crate: #[tokio::main] async fn main() | Async |
await Promise.all([a, b])await Task.WhenAll(a, b) | tokio::join!(a, b) | Async |
Promise.race; the others keep runningTask.WhenAny; the others keep running | tokio::select!; the others are dropped | Async |
Call it without awaitTask.Run(…) | tokio::spawn(async move { … }): returns a JoinHandle | Async |
await new Promise((r) => setTimeout(r, 100))await Task.Delay(100) | tokio::time::sleep(Duration::from_millis(100)).await | Async |
AbortSignal.timeout(1000)await task.WaitAsync(TimeSpan.FromSeconds(1)) | tokio::time::timeout(Duration::from_secs(1), fut).await: a Result | Async |
Pass an AbortSignal all the way downPass a CancellationToken all the way down | Drop the future; it stops at its current .await | Async |
Move CPU-heavy work to a Workerawait Task.Run(() => Heavy()) | tokio::task::spawn_blocking(|| heavy()).await | Async |
Rarely needed: one thread runs your codeSemaphoreSlim(1, 1) held across await | tokio::sync::Mutex when the lock is held across .await | Async |
new Worker(file) from node:worker_threadsnew Thread(…), or Task.Run(…) | std::thread::spawn(move || …): returns a JoinHandle<T> | Threads |
Listen for the worker’s message eventthread.Join(), or await task | handle.join(): the closure’s value, or Err if it panicked | Threads |
| Workers get a copy of the dataLambdas capture locals; the GC keeps them alive | std::thread::scope(|s| …): threads borrow locals, and the scope waits for them | Threads |
postMessage and the message eventChannel<T>, BlockingCollection<T> | std::sync::mpsc::channel() returns (tx, rx); sending moves the value | Threads |
No locks: workers don’t share objectslock (gate) { … } | let mut data = m.lock().unwrap();: unlocked when data is dropped | Threads |
A SharedArrayBufferAny object, plus a lock | Arc<Mutex<T>>, with an Arc::clone per thread | Threads |
Atomics.add(view, 0, 1)Interlocked.Increment(ref count) | count.fetch_add(1, Ordering::Relaxed) on an AtomicU64 | Threads |
| Rarely a question: each worker has its own objectsRead the docs: “not guaranteed to be thread-safe” | The compiler checks Send (can move to a thread) and Sync (can be shared) | Send & Sync |
| Two threads changing one variable: impossible with ordinary objectsTwo threads changing one variable: compiles, loses updates | Compile error without a Mutex or an atomic | Send & Sync |
Testing & tooling
| In TypeScriptC# | Rust | Learn more |
|---|---|---|
| The Node.js installer, nvm or VoltaThe .NET SDK installer | rustup: installs rustc, cargo, clippy, rustfmt | Tooling |
npm initdotnet new console | cargo new app; cargo new --lib name for a library | Tooling |
tsc --noEmitdotnet build (no check-only build) | cargo check | Tooling |
node app.ts or tsx app.tsdotnet run | cargo run; program arguments after -- | Tooling |
tscdotnet build | cargo build: debug build in target/debug/ | Tooling |
A production bundledotnet publish | cargo build --release: optimized, in target/release/ | Tooling |
| ESLintRoslyn analyzers | cargo clippy; cargo clippy -- -D warnings in CI | Tooling |
Prettierdotnet format | cargo fmt; cargo fmt --check in CI | Tooling |
| Vitest or Jest, as a dev dependencyxUnit, NUnit or MSTest, in a test project | Built in: #[test] and cargo test | Tests |
vitest -t rejectsdotnet test --filter rejects | cargo test rejects: tests whose name contains it | Tests |
test("adds", () => { … })[Fact] public void Adds() | #[test] fn adds() { … } | Tests |
expect(actual).toEqual(expected)Assert.Equal(expected, actual) | assert_eq!(actual, expected); assert_ne! | Tests |
expect(() => f()).toThrow()Assert.Throws<T>(() => F()) | #[should_panic] for a panic; assert!(result.is_err()) for an error | Tests |
test.skip(…)[Fact(Skip = "reason")] | #[ignore = "reason"]; run with cargo test -- --ignored | Tests |
| A test that lets an error throwA test that lets an exception throw | A test returning Result<(), E>, so ? works inside | Tests |
A separate *.test.ts fileA separate test project | #[cfg(test)] mod tests in the same file; integration tests in tests/ | Tests |
/** JSDoc */ comments/// <summary> XML comments | /// Markdown comments; cargo doc --open | Tests |
| No runnable examples in docsNo runnable examples in docs | Doc tests: code blocks in /// comments run with cargo test | Tests |
| Decorators, which run at run timeSource generators | Macros: macro_rules! and procedural macros, run by the compiler | Macros |
JSON.stringify(order)JsonSerializer.Serialize(order) | serde_json::to_string(&order)? with #[derive(Serialize)] | Macros & serde |
JSON.parse(text) returns anyJsonSerializer.Deserialize<Order>(text) | serde_json::from_str::<Order>(&text)? with #[derive(Deserialize)]; missing fields are errors | Macros & serde |
camelCase property namesJsonSerializerDefaults.Web, [JsonPropertyName] | #[serde(rename_all = "camelCase")], #[serde(rename = "id")] | Macros & serde |
Not possible in the languageunsafe { … } with AllowUnsafeBlocks | unsafe { … }; #![forbid(unsafe_code)] to rule it out | unsafe & FFI |
A Node-API native addon[DllImport] or [LibraryImport] | unsafe extern "C" { fn strlen(s: *const c_char) -> usize; } | unsafe & FFI |
export function in a module[JSExport] in Blazor WebAssembly | #[wasm_bindgen] pub fn, built with wasm-pack build | WebAssembly |