Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    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#RustLearn more
    const total = 5;var total = 5; (no read-only locals)let total = 5;: immutable by defaultVariables
    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 eitherVariables
    Redeclaring a name: compile errorRedeclaring a name: error CS0128Shadowing: let input = input.trim();, even with a new typeVariables
    const MAX_RETRIES = 3; at module levelconst int MaxRetries = 3;const MAX_RETRIES: u32 = 3;: type required, copied into every useVariables
    A module-level letA static fieldstatic COUNT: AtomicU64 = AtomicU64::new(0);: immutable unless thread-safeVariables
    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#RustLearn more
    number (whole numbers)inti32: the default for whole numbersPrimitive types
    number or bigintlong, ulongi64, u64Primitive types
    number, or one element of a Uint8Arraybyteu8; binary data is &[u8] or Vec<u8>Primitive types
    number for an index or lengthint for an index or Countusize: what len() returns and indexing takesPrimitive types
    number (64-bit float)double, floatf64, f32Primitive types
    No decimal typedecimal for moneyNone in std: integer cents in an i64, or the rust_decimal cratePrimitive types
    booleanboolboolPrimitive types
    A one-character stringchar: one UTF-16 code unitchar: one Unicode scalar value, 4 bytes; literal 'a'Primitive types
    0xFF, 0b1010, 1_000_000, 10n0xFF, 0b1010, 1_000_000, 10L, 1.5f0xFF, 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 fiti32::try_from(big): returns a ResultPrimitive types
    n | 0: cut to 32 bits(int)big: cuts off bitsbig as i32: cuts off bits on purposePrimitive types
    Math.trunc(x)(int)xx as i32: truncates, and saturates at the type’s limitsPrimitive 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 wantPrimitive 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 integersPrimitive 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, .1Primitive types
    number[] (can always grow)int[] (length not in the type)[i32; 3]: the length is part of the typePrimitive 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 typeStructs
    typeof x at run timex.GetType()None: no type information at run time; generics are compiled per typeGenerics

    Strings

    In TypeScriptC#RustLearn more
    stringstring, or StringBuilder to build oneString: owned, growable, UTF-8Slices
    string (a parameter or a piece of one)ReadOnlySpan<char>&str: a borrowed view of UTF-8 textSlices
    "hello""hello" (interned)"hello" is a &'static str; String::from("hello") or "hello".to_string() for an owned oneSlices
    `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-printStandard traits
    console.log("total", total)Debug.WriteLine(total)dbg!(total): prints file, line, expression and valueMacros
    x.toFixed(2)$"{x:F2}"format!("{x:.2}")Strings
    s.length: UTF-16 code unitss.Length: UTF-16 code unitss.len(): bytes; s.chars().count(): charactersStrings
    a + ba + &b (moves a), or format!("{a}{b}")Strings
    s += "!"sb.Append("!")s.push_str("!"), s.push('!'); s must be mutStrings
    parts.join(", ")string.Join(", ", parts)parts.join(", ")Strings
    s.split(",")s.Split(',')s.split(','): a lazy iterator of &strStrings
    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 missings.find("x"): Option<usize>, a byte offsetStrings
    s.replaceAll("a", "b")s.Replace("a", "b")s.replace("a", "b"): replaces every matchStrings
    s.slice(0, 5): a copys[..5]: a copy; s.AsSpan(..5): a view&s[..5]: a view; byte offsets, panics inside a characterSlices
    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 tooStrings
    a === ba == ba == b, also between String and &strStrings
    new TextDecoder().decode(bytes)Encoding.UTF8.GetString(bytes)String::from_utf8(bytes): a Result; String::from_utf8_lossy(&bytes) never failsStrings
    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() workStandard traits

    Functions & closures

    In TypeScriptC#RustLearn more
    function add(a: number, b: number): numberstatic int Add(int a, int b)fn add(a: i32, b: i32) -> i32Functions
    return a + b;a + b as the last expression, with no semicolon; return for early exitsFunctions
    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 statementA 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 functionFunctions
    Overload signaturesMethod overloadsNone: 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! canMacros
    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 valueReturn a tuple, an Option or a ResultOption
    Wrap the number in an object to change itref int count, called with ref ncount: &mut i32, called with &mut n, changed with *count += 1References
    An inner function that uses outer variablesA local function that uses outer variablesAn inner fn can’t see outer variables; use a closureClosures
    (x) => x * 2x => x * 2|x| x * 2Closures
    (x: number): number => { … }(int x) => { … }|x: i32| -> i32 { … }Closures
    Captures see the variable itselfCaptures live in a shared hidden objectCaptured by &, &mut or by move, depending on what the body doesClosures
    Captures stay alive automaticallyCaptures stay alive automaticallymove |x| x + offset: the closure owns what it capturesClosures
    A callback that changes a captured counterA lambda that changes a captured counterlet mut inc = || count += 1;: an FnMut, and inc must be mutClosures
    rule: (n: number) => numberFunc<int, int> rulerule: impl Fn(i32) -> i32 (a generic, the default)Closures
    A field holding a functionA Func<int, int> field or a list of themBox<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#RustLearn more
    if (x > 0) { … } else { … }if x > 0 { … } else { … }: no parentheses, braces requiredLoops & conditionals
    cond ? a : bif cond { a } else { b }: if is an expressionLoops & conditionals
    while (n > 0) { … }while n > 0 { … }Loops & conditionals
    while (true) { … break; }loop { … break; }Loops & conditionals
    A variable set before breakA variable set before breaklet found = loop { break value; };Loops & conditionals
    for (let i = 0; i < 10; i++)for (var i = 0; i < 10; i++)for i in 0..10Loops & conditionals
    for (let i = 0; i <= 10; i++)for (var i = 0; i <= 10; i++)for i in 0..=10Loops & 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-throughMatch
    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 exceptionMissing case: compile error E0004Match
    point.x === 0point is { X: 0 }Point { x: 0, .. } in a pattern; .. skips the other fieldsMatch
    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#RustLearn more
    T | undefined, T | nullT?Option<T>: Some(value) or NoneOption
    undefined, nullnullNone; a present value is Some(x)Option
    Using it unchecked: error with strictNullChecksUsing it unchecked: warning CS8602Compile error: an Option<T> is not a TOption
    value ?? fallbackvalue.unwrap_or(fallback); unwrap_or_else(|| …) computes it lazilyOption
    user?.address?.cityuser?.Address?.Cityuser.and_then(|u| u.address), or ? in a function that returns OptionOption
    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 NoneOption
    A function that throws; the signature doesn’t say soA method that throws; the signature doesn’t say soReturns 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 fallbackresult.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 FromResult & ?
    Missing value becomes a thrown errorNull becomes a thrown exceptionopt.ok_or(MyError::Missing)?; result.ok() goes the other wayResult & ?
    class ConfigError extends Errorclass ConfigException : ExceptionAn enum that implements Display and std::error::ErrorCustom errors
    Exported error classes in a libraryCustom exception classes in a library#[derive(thiserror::Error)] on an enum, with #[error("…")] per variantCustom errors
    catch (e: unknown) and log itcatch (Exception e) and log itanyhow::Result<T> plus .context("loading config")? in an applicationCustom errors
    throw new RangeError(…) for a bugthrow new ArgumentOutOfRangeException(…) for a bugpanic!("…"), assert!(cond): the program stopsCustom errors
    Uncaught exception in the entry point: exit code 1Unhandled exception in Main: the process crashesfn main() -> Result<(), Box<dyn Error>>: prints Error: …, exits with code 1Result & ?
    finally { file.close(); }finally { file.Dispose(); }Nothing to write: Drop runs when the owner goes out of scopeDrop

    Collections & iterators

    In TypeScriptC#RustLearn 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 mutCollections
    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 placeCollections
    xs.lengthxs.Countxs.len(), xs.is_empty()Collections
    xs[i]: undefined if out of rangexs[i]: throws if out of rangexs[i] panics; xs.get(i) returns an OptionCollections
    xs[0], xs.at(-1)xs[0], xs[^1]xs.first(), xs.last(): OptionsCollections
    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 copySlices
    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] = vm.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 loopCollections
    for (const [k, v] of m)foreach (var (k, v) in d)for (k, v) in &m; order is unspecifiedCollections
    Sort the keys yourselfSortedDictionary<TKey, TValue>BTreeMap<K, V>: always in key orderCollections
    Set<T>HashSet<T>HashSet<T>; BTreeSet<T> for sortedCollections
    xs.push(x) and xs.shift()Queue<T>: Enqueue, DequeueVecDeque<T>: push_back, pop_frontCollections
    xs.map(f): runs at oncexs.Select(f): lazyxs.iter().map(f): lazy, runs when consumedLazy 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 OptionLazy 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): OptionsLazy 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 enumerationUsing a consumed iterator again: compile error E0382Lazy iterators
    A generator: function* with yieldIEnumerable<T> with yield returnA struct with impl Iterator: type Item and fn nextLazy iterators

    Structs, enums & methods

    In TypeScriptC#RustLearn more
    class Point { x = 0; y = 0; }, or an interfaceclass, struct or recordstruct 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 literalStructs
    constructor(x: number, y: number)A constructor, or a primary constructorfn 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 fieldsStructs
    Methods inside the classMethods inside the typeimpl Point { fn len(&self) -> f64 { … } }Structs
    this, implicitthis, implicitself, &self or &mut self, written as the first parameterStructs
    A method that changes thisA method that changes fieldsfn add(&mut self, …); the caller’s variable must be mutStructs
    No equivalentNo equivalentfn finish(self): takes ownership, so the value can’t be used afterwardsStructs
    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) -> f64Structs
    private or #fieldprivate fieldsFields are private to the module unless marked pubModules
    A branded typereadonly record struct UserId(int Value)struct UserId(u64); (a newtype), read as id.0Structs
    Field initializersField initializers, default(T)#[derive(Default)], then Config::default()Standard traits
    class B extends Aclass B : ANone: put an A field inside B; share behavior with traitsStructs
    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 compilesLight::Red as i32; a value outside the list is impossibleEnums
    A discriminated union with a kind tagAn abstract record with a sealed record per caseenum Shape { Circle { r: f64 }, Rect { w: f64, h: f64 } }Enums
    switch (shape.kind)switch expression with type patternsmatch shape { Shape::Circle { r } => …, Shape::Rect { w, h } => … }Enums
    Functions that take the unionMethods on the base recordimpl 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#RustLearn 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 : IShapeimpl Shape for Square { … }, a block of its ownTraits
    An abstract base class method with a bodyA default interface methodA default method with a body in the trait; callable on the type directlyTraits
    A plain functionAn extension methodYour own trait implemented for the type: impl Shout for strTraits
    Not allowed in an interfacestatic abstract interface membersAssociated 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, INamedT: Shape + Display, or where T: Shape + DisplayGenerics
    a >= b works on any Twhere T : IComparable<T> and CompareToT: PartialOrd, then a >= bGenerics
    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 constraintimpl<T: PartialOrd> Pair<T> { … }: methods only for some TGenerics
    Type parameters erasedReal types at run timeOne compiled copy per type used (monomorphization)Generics
    shape: ShapeIShape shapeshape: &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 variesimpl vs. dyn
    A generic parameter on the interfaceA generic parameter on the interfaceAn associated type: type Item;, used as Iterator<Item = u32>Lazy iterators
    A toString() methodOverride ToString()impl DisplayStandard 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 EqStandard traits
    A compare function passed to sortIComparable<T>, IComparer<T>#[derive(PartialOrd, Ord)], or impl OrdStandard traits
    Conversion functions you nameimplicit and explicit operatorsimpl From<A> for B, then B::from(a) or a.into(); TryFrom when it can failStandard 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#RustLearn more
    The garbage collector frees memory laterThe garbage collector frees memory laterThe owner frees it when it goes out of scopeOwnership
    The engine decides where data livesstruct or class decides, then the runtimeYou decide, through the types you pick; String and Vec keep their data on the heapStack & heap
    const b = a; shares one arrayvar b = a; shares one List<T>let b = a; moves it; using a afterwards is error E0382Ownership
    Numbers are copiedValue types are copiedTypes that implement Copy are copied: integers, floats, bool, charCopy & Clone
    { ...obj } or structuredClone(obj)with, or a copy constructor.clone(): a visible, deep copy of what the value ownsCopy & Clone
    Nothing to opt intoDeclare it as a struct#[derive(Clone, Copy)] if every field is CopyCopy & Clone
    Pass the object; the function shares itPass the object; in for a large struct&T: lend it to readReferences
    Pass the object and change itPass the object; ref for a struct&mut T: lend it to changeReferences
    Pass the object and store itPass the object and store itT: ownership moves inChoosing parameter types
    Two writers to one object: allowedTwo writers to one object: allowedTwo &mut at once: error E0499References
    Changing an array while looping over it: allowedChanging a list while enumerating it: InvalidOperationExceptionError E0502 at compile timeReferences
    No dangling references; the GC keeps data aliveNo dangling references; the GC keeps data aliveA reference that outlives its value: error E0597References
    No equivalentNo equivalentLifetimes: fn longest<'a>(a: &'a str, b: &'a str) -> &'a strLifetimes
    Any field can refer to any objectA ref struct holding a Span<T>struct Highlight<'a> { text: &'a str }: can’t outlive the textLifetimes
    No equivalentNo equivalent (static means a type member)&'static str: valid for the whole program; T: 'static: holds no expiring borrowLifetimes
    Every object is on the heap alreadyBoxing a struct into object, implicitlyBox::new(value): one heap allocation, always explicitStack & heap
    Every object can be sharedEvery class instance can be sharedRc<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 referenceRc<RefCell<T>> on one thread; Arc<Mutex<T>> across threadsShared ownership
    Parent and child point at each other; the GC copesParent and child point at each other; the GC copesChild to parent with Weak<T>, or the cycle leaksShared ownership
    using res = … with [Symbol.dispose]()using var res = … with IDisposableAutomatic for every value; impl Drop adds your own cleanupDrop
    Call the close method earlyCall Dispose() earlydrop(value); later uses are compile errorsDrop
    Return a string either wayReturn a string either wayCow<'a, str>: borrowed when unchanged, owned when changedDrop & smart pointers

    Modules & packages

    In TypeScriptC#RustLearn more
    A file is a moduleA namespace, independent of filesmod cart; loads cart.rs; mod cart { … } inlineModules
    Private to the file until exportedprivate members, internal typesPrivate to the module (and modules inside it) by defaultModules
    exportpublicpubModules
    Left out of the package’s exports mapinternalpub(crate)Modules
    import { total } from "./cart.js";using Shop.Cart;use crate::shop::cart::total;Modules
    export { total } from "./cart.js";No equivalentpub use cart::total;Modules
    "../" and "./" pathsNamespaces are absolutesuper:: (parent), self:: (this module), crate:: (root)Modules
    package.json, tsconfig.jsonMyApp.csprojCargo.tomlTooling
    package-lock.json, pnpm-lock.yamlpackages.lock.json (opt-in)Cargo.lockTooling
    npmjs.comnuget.orgcrates.ioTooling
    npm install zoddotnet add package Serilogcargo add serde --features deriveTooling
    npm install -D vitestA package in the test projectcargo 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" pinsTooling
    A bin entry, or main / exports<OutputType>Exe</OutputType>, or a class librarysrc/main.rs (binary crate) or src/lib.rs (library crate)Crates & workspaces
    npm or pnpm workspacesA solution with project referencesA Cargo workspace: [workspace] in the root Cargo.tomlCrates & workspaces
    "billing": "workspace:*"<ProjectReference Include="../Billing/Billing.csproj" />billing = { path = "../billing" }Crates & workspaces
    Separate add-on packagesSeparate add-on packagesCargo 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#RustLearn more
    async function load(): Promise<User>async Task<User> LoadAsync()async fn load() -> UserAsync
    await load()await LoadAsync()load().await: postfixAsync
    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 inAdd 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 runningtokio::select!; the others are droppedAsync
    Call it without awaitTask.Run(…)tokio::spawn(async move { … }): returns a JoinHandleAsync
    await new Promise((r) => setTimeout(r, 100))await Task.Delay(100)tokio::time::sleep(Duration::from_millis(100)).awaitAsync
    AbortSignal.timeout(1000)await task.WaitAsync(TimeSpan.FromSeconds(1))tokio::time::timeout(Duration::from_secs(1), fut).await: a ResultAsync
    Pass an AbortSignal all the way downPass a CancellationToken all the way downDrop the future; it stops at its current .awaitAsync
    Move CPU-heavy work to a Workerawait Task.Run(() => Heavy())tokio::task::spawn_blocking(|| heavy()).awaitAsync
    Rarely needed: one thread runs your codeSemaphoreSlim(1, 1) held across awaittokio::sync::Mutex when the lock is held across .awaitAsync
    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 taskhandle.join(): the closure’s value, or Err if it panickedThreads
    Workers get a copy of the dataLambdas capture locals; the GC keeps them alivestd::thread::scope(|s| …): threads borrow locals, and the scope waits for themThreads
    postMessage and the message eventChannel<T>, BlockingCollection<T>std::sync::mpsc::channel() returns (tx, rx); sending moves the valueThreads
    No locks: workers don’t share objectslock (gate) { … }let mut data = m.lock().unwrap();: unlocked when data is droppedThreads
    A SharedArrayBufferAny object, plus a lockArc<Mutex<T>>, with an Arc::clone per threadThreads
    Atomics.add(view, 0, 1)Interlocked.Increment(ref count)count.fetch_add(1, Ordering::Relaxed) on an AtomicU64Threads
    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 updatesCompile error without a Mutex or an atomicSend & Sync

    Testing & tooling

    In TypeScriptC#RustLearn more
    The Node.js installer, nvm or VoltaThe .NET SDK installerrustup: installs rustc, cargo, clippy, rustfmtTooling
    npm initdotnet new consolecargo new app; cargo new --lib name for a libraryTooling
    tsc --noEmitdotnet build (no check-only build)cargo checkTooling
    node app.ts or tsx app.tsdotnet runcargo run; program arguments after --Tooling
    tscdotnet buildcargo build: debug build in target/debug/Tooling
    A production bundledotnet publishcargo build --release: optimized, in target/release/Tooling
    ESLintRoslyn analyzerscargo clippy; cargo clippy -- -D warnings in CITooling
    Prettierdotnet formatcargo fmt; cargo fmt --check in CITooling
    Vitest or Jest, as a dev dependencyxUnit, NUnit or MSTest, in a test projectBuilt in: #[test] and cargo testTests
    vitest -t rejectsdotnet test --filter rejectscargo test rejects: tests whose name contains itTests
    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 errorTests
    test.skip(…)[Fact(Skip = "reason")]#[ignore = "reason"]; run with cargo test -- --ignoredTests
    A test that lets an error throwA test that lets an exception throwA test returning Result<(), E>, so ? works insideTests
    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 --openTests
    No runnable examples in docsNo runnable examples in docsDoc tests: code blocks in /// comments run with cargo testTests
    Decorators, which run at run timeSource generatorsMacros: macro_rules! and procedural macros, run by the compilerMacros
    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 errorsMacros & serde
    camelCase property namesJsonSerializerDefaults.Web, [JsonPropertyName]#[serde(rename_all = "camelCase")], #[serde(rename = "id")]Macros & serde
    Not possible in the languageunsafe { … } with AllowUnsafeBlocksunsafe { … }; #![forbid(unsafe_code)] to rule it outunsafe & 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 buildWebAssembly