Skip to content
binshelf/ rust

Search lessons

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

    Compare Rust with

    Reference

    Migration FAQ

    Short answers to "how do I do this in Rust?" for the habits you bring from class-based, garbage-collected languages, each with a checked example and links to the lessons that explain it.

    You already know how to solve these problems in TypeScriptC#. Each answer below gives the Rust way in a sentence or two, a checked example, when to pick which option, and the lessons that cover it in depth.

    How do I do inheritance?

    Rust has no class inheritance. Reuse data by putting one struct inside another, and share behavior through a trait: its methods without a body play the part of abstract methods, and its default methods play the part of shared base-class code.

    TypeScript
    animals.ts
    abstract class Animal {
      readonly name: string;
    
      constructor(name: string) {
        this.name = name;
      }
    
      abstract sound(): string;
    
      describe(): string {
        return `${this.name} says ${this.sound()}`;
      }
    }
    
    class Dog extends Animal {
      sound(): string {
        return "woof";
      }
    }
    
    class Cat extends Animal {
      sound(): string {
        return "meow";
      }
    }
    
    const animals: Animal[] = [new Dog("Rex"), new Cat("Tom")];
    for (const animal of animals) {
      console.log(animal.describe());
    }
    C#
    Animals.cs
    List<Animal> animals = [new Dog("Rex"), new Cat("Tom")];
    foreach (var animal in animals)
    {
        Console.WriteLine(animal.Describe());
    }
    
    abstract class Animal(string name)
    {
        public string Name { get; } = name;
    
        public abstract string Sound();
    
        public string Describe() => $"{Name} says {Sound()}";
    }
    
    class Dog(string name) : Animal(name)
    {
        public override string Sound() => "woof";
    }
    
    class Cat(string name) : Animal(name)
    {
        public override string Sound() => "meow";
    }
    Rust
    trait Animal {
        fn name(&self) -> &str;
        fn sound(&self) -> &str;
    
        fn describe(&self) -> String {
            format!("{} says {}", self.name(), self.sound())
        }
    }
    
    struct Dog {
        name: String,
    }
    
    struct Cat {
        name: String,
    }
    
    impl Animal for Dog {
        fn name(&self) -> &str {
            &self.name
        }
    
        fn sound(&self) -> &str {
            "woof"
        }
    }
    
    impl Animal for Cat {
        fn name(&self) -> &str {
            &self.name
        }
    
        fn sound(&self) -> &str {
            "meow"
        }
    }
    
    fn main() {
        let animals: Vec<Box<dyn Animal>> = vec![
            Box::new(Dog {
                name: String::from("Rex"),
            }),
            Box::new(Cat {
                name: String::from("Tom"),
            }),
        ];
        for animal in &animals {
            println!("{}", animal.describe());
        }
    }

    Output

    Rex says woof
    Tom says meow

    A trait has no fields, so each type stores its own name and exposes it through a method. There’s also no super.describe(): an override can’t call the default it replaces, so put shared logic in a plain function that both can call.

    When to use what: a struct field for shared data; a trait with default methods for shared behavior; Vec<Box<dyn Animal>> for a list of mixed types; an enum instead when you know every kind up front.

    Learn more: Structs & impl blocks, Traits, impl Trait vs. dyn Trait

    How do I overload a method?

    You don’t: every Rust function has exactly one parameter list. Give the variants different names, as the standard library does with String::new and String::with_capacity, or make one function generic so it accepts several argument types.

    struct Label {
        text: String,
        width: usize,
    }
    
    impl Label {
        // `impl Into<String>` accepts a `&str`, a `String`, or anything else that converts
        fn new(text: impl Into<String>) -> Self {
            let text = text.into();
            let width = text.len();
            Self { text, width }
        }
    
        fn with_width(text: impl Into<String>, width: usize) -> Self {
            Self {
                text: text.into(),
                width,
            }
        }
    }
    
    let ok = Label::new("ok");
    let cancel = Label::new(String::from("cancel"));
    let save = Label::with_width("save", 8);
    for label in [ok, cancel, save] {
        println!("[{:<width$}]", label.text, width = label.width);
    }

    Output

    [ok]
    [cancel]
    [save    ]

    When to use what: a separate, descriptive name (new, with_width, from_file) when the variants do different things; a generic parameter such as impl Into<String> or impl AsRef<Path> when they do the same thing with different input types.

    Learn more: Functions, expressions & statements, Structs & impl blocks, Standard traits

    How do I give a parameter a default value?

    Rust has no default or optional parameters. Take an Option<T> for an argument the caller may leave out. For a group of settings, put them in a struct that implements Default and let the caller override only what changes with ..Default::default().

    #[derive(Debug)]
    struct RetryPolicy {
        attempts: u32,
        delay_ms: u64,
        jitter: bool,
    }
    
    impl Default for RetryPolicy {
        fn default() -> Self {
            Self {
                attempts: 3,
                delay_ms: 100,
                jitter: true,
            }
        }
    }
    
    fn greet(name: Option<&str>) -> String {
        format!("Hello, {}!", name.unwrap_or("world"))
    }
    
    println!("{}", greet(None));
    println!("{}", greet(Some("Ada")));
    
    let policy = RetryPolicy {
        attempts: 5,
        ..Default::default()
    };
    println!("{policy:?}");

    Output

    Hello, world!
    Hello, Ada!
    RetryPolicy { attempts: 5, delay_ms: 100, jitter: true }

    When a value has many optional settings, or some combinations are invalid, use a builder: a separate type whose methods each set one option and return the builder, ending in build(). Each method takes self by value, so the calls chain.

    struct Request {
        url: String,
        method: String,
        timeout_secs: u64,
    }
    
    struct RequestBuilder {
        url: String,
        method: String,
        timeout_secs: u64,
    }
    
    impl Request {
        fn builder(url: &str) -> RequestBuilder {
            RequestBuilder {
                url: url.to_string(),
                method: String::from("GET"),
                timeout_secs: 30,
            }
        }
    }
    
    impl RequestBuilder {
        fn method(mut self, method: &str) -> Self {
            self.method = method.to_string();
            self
        }
    
        fn timeout_secs(mut self, secs: u64) -> Self {
            self.timeout_secs = secs;
            self
        }
    
        fn build(self) -> Request {
            Request {
                url: self.url,
                method: self.method,
                timeout_secs: self.timeout_secs,
            }
        }
    }
    
    let get = Request::builder("https://example.com").build();
    let post = Request::builder("https://example.com/orders")
        .method("POST")
        .timeout_secs(5)
        .build();
    for request in [get, post] {
        let Request {
            url,
            method,
            timeout_secs,
        } = request;
        println!("{method} {url} ({timeout_secs}s)");
    }

    Output

    GET https://example.com (30s)
    POST https://example.com/orders (5s)

    When to use what: Option<T> for one or two optional arguments; a Default struct with ..Default::default() for a settings bag; a builder when there are many options or build() needs to validate them.

    Learn more: Functions, expressions & statements, Option instead of null, Standard traits

    How do I make a field optional or nullable?

    Use Option<T>. A String can never be null; an Option<String> is either Some(text) or None, and the compiler won’t let you use it as text until you’ve handled None.

    TypeScript
    person.ts
    type Person = { first: string; middle?: string; last: string };
    
    function fullName(person: Person): string {
      if (person.middle !== undefined) {
        return `${person.first} ${person.middle} ${person.last}`;
      }
      return `${person.first} ${person.last}`;
    }
    
    const ada: Person = { first: "Ada", last: "Lovelace" };
    const grace: Person = { first: "Grace", middle: "Brewster", last: "Hopper" };
    console.log(fullName(ada));
    console.log(fullName(grace));
    console.log(ada.middle ?? "(no middle name)");
    C#
    Person.cs
    var ada = new Person("Ada", null, "Lovelace");
    var grace = new Person("Grace", "Brewster", "Hopper");
    Console.WriteLine(FullName(ada));
    Console.WriteLine(FullName(grace));
    Console.WriteLine(ada.Middle ?? "(no middle name)");
    
    static string FullName(Person person) =>
        person.Middle is string middle
            ? $"{person.First} {middle} {person.Last}"
            : $"{person.First} {person.Last}";
    
    record Person(string First, string? Middle, string Last);
    Rust
    struct Person {
        first: String,
        middle: Option<String>,
        last: String,
    }
    
    fn full_name(person: &Person) -> String {
        match &person.middle {
            Some(middle) => format!("{} {middle} {}", person.first, person.last),
            None => format!("{} {}", person.first, person.last),
        }
    }
    
    fn main() {
        let ada = Person {
            first: String::from("Ada"),
            middle: None,
            last: String::from("Lovelace"),
        };
        let grace = Person {
            first: String::from("Grace"),
            middle: Some(String::from("Brewster")),
            last: String::from("Hopper"),
        };
        println!("{}", full_name(&ada));
        println!("{}", full_name(&grace));
        println!("{}", ada.middle.as_deref().unwrap_or("(no middle name)"));
    }

    Output

    Ada Lovelace
    Grace Brewster Hopper
    (no middle name)

    as_deref() turns &Option<String> into Option<&str>, so unwrap_or can fall back to a string literal without moving the field out.

    When to use what: Option<T> whenever “not there” is a normal state; unwrap_or for ??for ??; map and and_then for ?.?.; ok_or when a missing value should become an error.

    Learn more: Option instead of null, if let, while let & let-else

    How do I throw and catch exceptions?

    Rust has no exceptions. A function that can fail returns Result<T, E>, either Ok(value) or Err(error). Writing ? after a call passes the error up to the caller, like letting an exception propagate, and match handles it, like catch.

    TypeScript
    port.ts
    function parsePort(text: string): number {
      const port = Number(text);
      if (!Number.isInteger(port) || port < 1 || port > 65535) {
        throw new Error(`invalid port: ${text}`);
      }
      return port;
    }
    
    for (const input of ["8080", "http", "0"]) {
      try {
        console.log(`port ${parsePort(input)}`);
      } catch (error) {
        console.log(`error: ${(error as Error).message}`);
      }
    }
    C#
    Port.cs
    foreach (var input in new[] { "8080", "http", "0" })
    {
        try
        {
            Console.WriteLine($"port {ParsePort(input)}");
        }
        catch (FormatException error)
        {
            Console.WriteLine($"error: {error.Message}");
        }
    }
    
    static int ParsePort(string text)
    {
        if (!int.TryParse(text, out var port) || port < 1 || port > 65535)
        {
            throw new FormatException($"invalid port: {text}");
        }
        return port;
    }
    Rust
    fn parse_port(text: &str) -> Result<u16, String> {
        let port: u16 = text.parse().map_err(|_| format!("invalid port: {text}"))?;
        if port == 0 {
            return Err(format!("invalid port: {text}"));
        }
        Ok(port)
    }
    
    fn main() {
        for input in ["8080", "http", "0"] {
            match parse_port(input) {
                Ok(port) => println!("port {port}"),
                Err(error) => println!("error: {error}"),
            }
        }
    }

    Output

    port 8080
    error: invalid port: http
    error: invalid port: 0

    The signature says the function can fail, and the caller can’t get at the u16 without dealing with the Err. For bugs, where the program can’t sensibly continue, there’s panic!, and .expect("why") panics with your message if a Result is an Err.

    When to use what: Result with ? for anything that can fail for reasons outside your code (input, files, network); a thiserror enum as the error type in a library; anyhow::Result in an application; panic! and expect only for bugs.

    Learn more: Result and the ? operator, Panics, custom errors, thiserror & anyhow

    How do I define an interface?

    Write a trait and implement it with impl Trait for Type. A type has to opt in explicitly: having methods with the right names isn’t enough. Unlike with most interfaces, you can also implement your own trait for a type you didn’t write, such as Vec or i32.

    trait Summary {
        fn summary(&self) -> String;
    }
    
    struct Article {
        title: String,
        words: u32,
    }
    
    impl Summary for Article {
        fn summary(&self) -> String {
            format!("{} ({} words)", self.title, self.words)
        }
    }
    
    // Your trait on a standard library type
    impl Summary for Vec<Article> {
        fn summary(&self) -> String {
            let words: u32 = self.iter().map(|article| article.words).sum();
            format!("{} articles, {words} words", self.len())
        }
    }
    
    fn print_summary(item: &impl Summary) {
        println!("{}", item.summary());
    }
    
    fn main() {
        let articles = vec![
            Article {
                title: String::from("Ownership"),
                words: 1200,
            },
            Article {
                title: String::from("Borrowing"),
                words: 900,
            },
        ];
        print_summary(&articles[0]);
        print_summary(&articles);
    }

    Output

    Ownership (1200 words)
    2 articles, 2100 words

    When to use what: a trait for any “can do X” contract; &impl Summary (or a generic T: Summary) for parameters; &dyn Summary or Box<dyn Summary> when you need to store different types together.

    Learn more: Traits, impl Trait vs. dyn Trait

    How do I write a generic function with constraints?

    Put a trait bound on the type parameter: fn best<T: Scored>(items: &[T]). Without a bound, the function can’t call any method on T, not even == or >; those need bounds too (PartialEq, PartialOrd).

    TypeScript
    best.ts
    interface Scored {
      score(): number;
    }
    
    class Player implements Scored {
      readonly name: string;
      readonly points: number;
    
      constructor(name: string, points: number) {
        this.name = name;
        this.points = points;
      }
    
      score(): number {
        return this.points;
      }
    }
    
    function best<T extends Scored>(items: T[]): T | undefined {
      let top: T | undefined;
      for (const item of items) {
        if (top === undefined || item.score() > top.score()) {
          top = item;
        }
      }
      return top;
    }
    
    const players = [new Player("Ada", 30), new Player("Grace", 45)];
    console.log(best(players)?.name ?? "nobody");
    console.log(best<Player>([])?.name ?? "nobody");
    C#
    Best.cs
    List<Player> players = [new("Ada", 30), new("Grace", 45)];
    Console.WriteLine(Best(players)?.Name ?? "nobody");
    Console.WriteLine(Best(new List<Player>())?.Name ?? "nobody");
    
    static T? Best<T>(List<T> items) where T : class, IScored
    {
        T? top = null;
        foreach (var item in items)
        {
            if (top is null || item.Score() > top.Score())
            {
                top = item;
            }
        }
        return top;
    }
    
    interface IScored
    {
        int Score();
    }
    
    record Player(string Name, int Points) : IScored
    {
        public int Score() => Points;
    }
    Rust
    trait Scored {
        fn score(&self) -> u32;
    }
    
    struct Player {
        name: String,
        points: u32,
    }
    
    impl Scored for Player {
        fn score(&self) -> u32 {
            self.points
        }
    }
    
    fn best<T: Scored>(items: &[T]) -> Option<&T> {
        items.iter().max_by_key(|item| item.score())
    }
    
    fn main() {
        let players = vec![
            Player {
                name: String::from("Ada"),
                points: 30,
            },
            Player {
                name: String::from("Grace"),
                points: 45,
            },
        ];
        let nobody: Vec<Player> = Vec::new();
        println!("{}", best(&players).map_or("nobody", |p| p.name.as_str()));
        println!("{}", best(&nobody).map_or("nobody", |p| p.name.as_str()));
    }

    Output

    Grace
    nobody

    Several bounds combine with + (T: Scored + Display), and long lists move to a where clause after the signature. The compiler makes one copy of best for each type you call it with, so the call is direct, with no lookup at run time.

    When to use what: <T: Trait> or impl Trait when each call uses one concrete type; a where clause when the bounds get long; dyn Trait when one collection must hold several types.

    Learn more: Generics, bounds & where, impl Trait vs. dyn Trait

    How do I do dependency injection?

    Pass dependencies in yourself; there’s no container in the language or standard library. Describe the dependency as a trait, and have the type that needs it hold either a generic parameter (the concrete type is fixed at compile time) or a Box<dyn Trait> (chosen at run time). Tests pass in a fake.

    trait Clock {
        fn hour(&self) -> u32;
    }
    
    // A test double; the real one would read the system time
    struct FixedClock(u32);
    
    impl Clock for FixedClock {
        fn hour(&self) -> u32 {
            self.0
        }
    }
    
    // Generic: one compiled version per clock type, no allocation
    struct Greeter<C> {
        clock: C,
    }
    
    impl<C: Clock> Greeter<C> {
        fn greet(&self, name: &str) -> String {
            let part = if self.clock.hour() < 12 {
                "morning"
            } else {
                "afternoon"
            };
            format!("Good {part}, {name}")
        }
    }
    
    // Trait object: the clock can be picked at run time
    struct Shop {
        clock: Box<dyn Clock>,
    }
    
    impl Shop {
        fn is_open(&self) -> bool {
            (9..17).contains(&self.clock.hour())
        }
    }
    
    let greeter = Greeter {
        clock: FixedClock(9),
    };
    println!("{}", greeter.greet("Ada"));
    
    let shop = Shop {
        clock: Box::new(FixedClock(20)),
    };
    println!("open: {}", shop.is_open());

    Output

    Good morning, Ada
    open: false

    When to use what: a generic parameter by default; Box<dyn Trait> when the implementation is chosen from configuration or several kinds are stored together; Arc<dyn Trait + Send + Sync> when the dependency is shared across threads, such as by the handlers of a web server.

    Learn more: Traits, Generics, bounds & where, impl Trait vs. dyn Trait

    How do I make a singleton or global state?

    First choice: create the value once in main and pass a reference to whatever needs it. When a global really is the right tool, Rust has four: a const for a fixed value, a static holding an atomic or a Mutex for state that changes, a LazyLock for a value built the first time it’s used, and a OnceLock for a value set once at startup.

    use std::collections::HashMap;
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::sync::{LazyLock, Mutex, OnceLock};
    
    const MAX_RETRIES: u32 = 3;
    static REQUESTS: AtomicU32 = AtomicU32::new(0);
    static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new());
    static APP_NAME: OnceLock<String> = OnceLock::new();
    static COUNTRIES: LazyLock<HashMap<&str, &str>> = LazyLock::new(|| {
        println!("building the table");
        HashMap::from([("fr", "France"), ("jp", "Japan")])
    });
    
    fn main() {
        APP_NAME
            .set(String::from("shop"))
            .expect("APP_NAME is set once, at startup");
        REQUESTS.fetch_add(1, Ordering::Relaxed);
        LOG.lock().unwrap().push(String::from("started"));
    
        println!("{} allows {MAX_RETRIES} retries", APP_NAME.get().unwrap());
        println!("before first use");
        println!("fr is {}", COUNTRIES["fr"]);
        println!("jp is {}", COUNTRIES["jp"]);
        let requests = REQUESTS.load(Ordering::Relaxed);
        let log = LOG.lock().unwrap().join(", ");
        println!("{requests} request, log: {log}");
    }

    Output

    shop allows 3 retries
    before first use
    building the table
    fr is France
    jp is Japan
    1 request, log: started

    Any thread can reach a static, so Rust won’t let you change a plain one: that would be a data race. That’s why the counter is an AtomicU32 and the log sits in a Mutex. static mut exists, but every use needs unsafe; don’t reach for it.

    When to use what: const for fixed values; LazyLock for a lookup table or a compiled pattern built on first use; OnceLock for configuration loaded at startup; an atomic or Mutex in a static for a counter or cache; passing the value as a parameter whenever you can.

    Learn more: Variables, mutability & shadowing, Reading Rust’s symbols, Threads, channels & shared state

    How do I handle events and callbacks?

    A callback is a closure. To let several listeners subscribe, store them as Box<dyn Fn(...)> in a Vec; for a one-off callback, take an impl Fn(...) parameter. Between threads or tasks, a channel usually replaces events: one side sends messages, the other loops over them.

    use std::sync::mpsc;
    use std::thread;
    
    type Handler = Box<dyn Fn(&str)>;
    
    struct Button {
        handlers: Vec<Handler>,
    }
    
    impl Button {
        fn on_click(&mut self, handler: impl Fn(&str) + 'static) {
            self.handlers.push(Box::new(handler));
        }
    
        fn click(&self, user: &str) {
            for handler in &self.handlers {
                handler(user);
            }
        }
    }
    
    fn main() {
        let mut button = Button {
            handlers: Vec::new(),
        };
        let label = String::from("Save");
        button.on_click(move |user| println!("{user} clicked {label}"));
        button.on_click(|user| println!("logged a click by {user}"));
        button.click("Ada");
    
        // Across threads, send messages through a channel instead
        let (sender, receiver) = mpsc::channel();
        let worker = thread::spawn(move || {
            for step in 1..=2 {
                sender.send(format!("step {step} done")).unwrap();
            }
        });
        for message in receiver {
            println!("{message}");
        }
        worker.join().unwrap();
    }

    Output

    Ada clicked Save
    logged a click by Ada
    step 1 done
    step 2 done

    move makes the first closure own label, and the 'static bound on on_click requires that: a stored handler can’t borrow a local that might be gone by the time the button is clicked. The for message in receiver loop ends when the worker finishes and its sender is dropped.

    When to use what: impl Fn parameters for a callback that’s called during the function; Vec<Box<dyn Fn>> for listeners you keep; std::sync::mpsc between threads; tokio::sync::mpsc (or broadcast for many listeners) between async tasks.

    Learn more: Closures & Fn, FnMut, FnOnce, Threads, channels & shared state

    How do I build a graph with cycles, like parent pointers?

    Two common ways. Keep every node in a Vec and link nodes by index (an “arena”); there are no references between nodes, so the borrow checker has nothing to object to. Or use Rc<T> for owning links and Weak<T> for the links back, with RefCell so links can be filled in after the nodes exist.

    struct Node {
        name: String,
        parent: Option<usize>,
        children: Vec<usize>,
    }
    
    #[derive(Default)]
    struct Tree {
        nodes: Vec<Node>,
    }
    
    impl Tree {
        fn add(&mut self, name: &str, parent: Option<usize>) -> usize {
            let id = self.nodes.len();
            self.nodes.push(Node {
                name: name.to_string(),
                parent,
                children: Vec::new(),
            });
            if let Some(parent) = parent {
                self.nodes[parent].children.push(id);
            }
            id
        }
    
        fn path(&self, mut id: usize) -> String {
            let mut names = vec![self.nodes[id].name.as_str()];
            while let Some(parent) = self.nodes[id].parent {
                names.push(&self.nodes[parent].name);
                id = parent;
            }
            names.reverse();
            names.join("/")
        }
    }
    
    fn main() {
        let mut tree = Tree::default();
        let root = tree.add("root", None);
        let docs = tree.add("docs", Some(root));
        let guide = tree.add("guide.md", Some(docs));
        println!("{}", tree.path(guide));
        println!("root has {} child", tree.nodes[root].children.len());
    }

    Output

    root/docs/guide.md
    root has 1 child

    With Rc, two nodes that own each other are never freed, because neither count reaches zero. TypeScriptC# doesn’t have that problem, because its garbage collector frees unreachable cycles. So with Rc, decide which direction owns (parent to child) and make the other direction a Weak.

    When to use what: indexes into a Vec for trees, graphs and anything you build and then query (it’s also fast and easy to clone); Rc and Weak when nodes are handed out and outlive any one container; never Rc in both directions.

    Learn more: Shared ownership & interior mutability, Vec, HashMap, HashSet & BTreeMap

    How do I share one object and change it from several places?

    By default, a value has one owner and can be changed through only one &mut at a time. Shared, changeable state is opt-in: Rc<RefCell<T>> within one thread, Arc<Mutex<T>> across threads. Often the simpler fix is to keep one owner and pass &mut to the code that needs to change it.

    use std::cell::RefCell;
    use std::rc::Rc;
    use std::sync::{Arc, Mutex};
    use std::thread;
    
    // One thread: Rc gives several owners, RefCell allows changes through them
    let cart = Rc::new(RefCell::new(Vec::new()));
    let same_cart = Rc::clone(&cart);
    same_cart.borrow_mut().push("tea");
    cart.borrow_mut().push("scones");
    println!("cart: {:?}", cart.borrow());
    
    // Several threads: Arc gives several owners, Mutex allows one writer at a time
    let total = Arc::new(Mutex::new(0));
    let handles: Vec<_> = (1..=3)
        .map(|n| {
            let total = Arc::clone(&total);
            thread::spawn(move || *total.lock().unwrap() += n)
        })
        .collect();
    for handle in handles {
        handle.join().unwrap();
    }
    println!("total: {}", total.lock().unwrap());

    Output

    cart: ["tea", "scones"]
    total: 6

    RefCell still enforces “many readers or one writer”, but at run time: a second borrow_mut() while the first is alive panics. The compiler stops you from using Rc or RefCell across threads; Arc and Mutex are the thread-safe versions.

    When to use what: one owner plus &mut whenever the structure allows it; Rc<RefCell<T>> for shared state in one thread; Arc<Mutex<T>> (or RwLock, or an atomic for a number) across threads.

    Learn more: Shared ownership & interior mutability, Send & Sync, References: &T and &mut T

    How do I write an enum that carries values?

    A Rust enum is more than named numbers: each variant can hold its own data, and match must handle every variant. It does the job of a discriminated uniona small record hierarchy with a switch expression.

    TypeScript
    payment.ts
    type Payment =
      | { kind: "cash" }
      | { kind: "card"; last4: string }
      | { kind: "voucher"; code: string; cents: number };
    
    function describe(payment: Payment): string {
      switch (payment.kind) {
        case "cash":
          return "cash";
        case "card":
          return `card ending ${payment.last4}`;
        case "voucher":
          return `voucher ${payment.code} worth ${payment.cents} cents`;
      }
    }
    
    const payments: Payment[] = [
      { kind: "cash" },
      { kind: "card", last4: "4242" },
      { kind: "voucher", code: "SPRING", cents: 500 },
    ];
    for (const payment of payments) {
      console.log(describe(payment));
    }
    C#
    Payment.cs
    Payment[] payments = [new Cash(), new Card("4242"), new Voucher("SPRING", 500)];
    foreach (var payment in payments)
    {
        Console.WriteLine(Describe(payment));
    }
    
    static string Describe(Payment payment) => payment switch
    {
        Cash => "cash",
        Card card => $"card ending {card.Last4}",
        Voucher voucher => $"voucher {voucher.Code} worth {voucher.Cents} cents",
        _ => throw new ArgumentOutOfRangeException(nameof(payment)),
    };
    
    abstract record Payment;
    record Cash : Payment;
    record Card(string Last4) : Payment;
    record Voucher(string Code, int Cents) : Payment;
    Rust
    enum Payment {
        Cash,
        Card { last4: String },
        Voucher { code: String, cents: u32 },
    }
    
    fn describe(payment: &Payment) -> String {
        match payment {
            Payment::Cash => String::from("cash"),
            Payment::Card { last4 } => format!("card ending {last4}"),
            Payment::Voucher { code, cents } => format!("voucher {code} worth {cents} cents"),
        }
    }
    
    fn main() {
        let payments = [
            Payment::Cash,
            Payment::Card {
                last4: String::from("4242"),
            },
            Payment::Voucher {
                code: String::from("SPRING"),
                cents: 500,
            },
        ];
        for payment in &payments {
            println!("{}", describe(payment));
        }
    }

    Output

    cash
    card ending 4242
    voucher SPRING worth 500 cents

    C# can’t tell that the three records are the only kinds of Payment, so the switch needs a _ arm. Add a variant to the Rust enum, and every match that doesn’t handle it stops compiling. For plain named numbers, write enum Level { Low = 1, High = 3 } and convert with Level::High as i32.

    When to use what: an enum when you know every kind up front and want the compiler to check each match; a trait when other code must be able to add new kinds.

    Learn more: Enums with data, Exhaustive match & destructuring

    How do I chain map, filter and reduce?

    Call .iter() on the collection, chain adapters such as filter and map, and finish with a consumer such as collect, sum or find. Adapters are lazy: nothing runs until the consumer asks for items.

    TypeScript
    orders.ts
    type Order = { customer: string; cents: number; paid: boolean };
    
    const orders: Order[] = [
      { customer: "Ada", cents: 1200, paid: true },
      { customer: "Grace", cents: 800, paid: false },
      { customer: "Linus", cents: 450, paid: true },
    ];
    
    const paidCustomers = orders.filter((order) => order.paid).map((order) => order.customer);
    const total = orders.filter((order) => order.paid).reduce((sum, order) => sum + order.cents, 0);
    const big = orders.find((order) => order.cents > 1000);
    console.log(paidCustomers.join(", "));
    console.log(`paid total: ${total}`);
    console.log(`first big order: ${big?.customer ?? "none"}`);
    C#
    Orders.cs
    List<Order> orders =
    [
        new("Ada", 1200, true),
        new("Grace", 800, false),
        new("Linus", 450, true),
    ];
    
    var paidCustomers = orders.Where(order => order.Paid).Select(order => order.Customer).ToList();
    var total = orders.Where(order => order.Paid).Sum(order => order.Cents);
    var big = orders.FirstOrDefault(order => order.Cents > 1000);
    Console.WriteLine(string.Join(", ", paidCustomers));
    Console.WriteLine($"paid total: {total}");
    Console.WriteLine($"first big order: {big?.Customer ?? "none"}");
    
    record Order(string Customer, int Cents, bool Paid);
    Rust
    struct Order {
        customer: String,
        cents: u32,
        paid: bool,
    }
    
    fn order(customer: &str, cents: u32, paid: bool) -> Order {
        Order {
            customer: customer.to_string(),
            cents,
            paid,
        }
    }
    
    fn main() {
        let orders = [
            order("Ada", 1200, true),
            order("Grace", 800, false),
            order("Linus", 450, true),
        ];
    
        let paid_customers: Vec<&str> = orders
            .iter()
            .filter(|order| order.paid)
            .map(|order| order.customer.as_str())
            .collect();
        let total: u32 = orders.iter().filter(|o| o.paid).map(|o| o.cents).sum();
        let big = orders.iter().find(|order| order.cents > 1000);
        let big_customer = big.map_or("none", |order| order.customer.as_str());
        println!("{}", paid_customers.join(", "));
        println!("paid total: {total}");
        println!("first big order: {big_customer}");
    }

    Output

    Ada, Linus
    paid total: 1650
    first big order: Ada

    The names mostly carry over: filter (filterWhere), map (mapSelect), flat_map (flatMapSelectMany), fold (reduceAggregate), any and all (some and everyAny and All), find (findFirstOrDefault), position (findIndexFindIndex), enumerate for the index, and collect (the new arrayToList). collect builds whatever type you ask for: a Vec, a HashMap, a String, or a Result<Vec<_>, _> that stops at the first error.

    When to use what: .iter() to read the items, .iter_mut() to change them in place, .into_iter() to take ownership of them; a plain for loop when the body has side effects or early returns.

    Learn more: Lazy iterators, Closures & Fn, FnMut, FnOnce

    How do I format strings and interpolate values?

    format! builds a String and println! prints one; both take a format string with {} placeholders that the compiler checks. A variable name can go inside the braces ({name}), but an expression such as {user.name} can’t: pass it as an argument instead.

    let name = "Ada";
    let price = 1234.5;
    let items = ["tea", "scones"];
    let n = 42;
    
    println!("Hello, {name}!");
    println!("{name} has {} items", items.len());
    println!("total: {price:.2}");
    println!("[{name:>6}] [{name:<6}] [{name:^7}]");
    println!("{n:05} {n:x} {n:b}");
    println!("debug: {items:?}");
    
    let line = format!("{name} paid {price:.1}");
    println!("{line} ({} bytes)", line.len());

    Output

    Hello, Ada!
    Ada has 2 items
    total: 1234.50
    [   Ada] [Ada   ] [  Ada  ]
    00042 2a 101010
    debug: ["tea", "scones"]
    Ada paid 1234.5 (15 bytes)

    {} uses the type’s Display implementation (text for users) and {:?} uses Debug (text for developers, which #[derive(Debug)] writes for you). Write {{ and }} for literal braces. To make your own type work with {}, implement Display; .to_string() then works too.

    When to use what: format! to build text; println! and eprintln! to print to stdout and stderr; push_str to append to a String you’re building; write! to format into a String or file without an extra allocation.

    Learn more: Strings: UTF-8 vs UTF-16, Standard traits, Macros & serde

    How do I read and write files?

    For a whole file, use std::fs::read_to_string and std::fs::write. To go line by line, wrap a File in a BufReader and call .lines(); to write piece by piece, wrap it in a BufWriter and use writeln!. Every call returns an io::Result, so ? passes errors up.

    use std::fs::{self, File};
    use std::io::{self, BufRead, BufReader, BufWriter, Write};
    
    fn main() -> io::Result<()> {
        let path = std::env::temp_dir().join("migration-faq-notes.txt");
    
        fs::write(&path, "first line\nsecond line\n")?;
        let text = fs::read_to_string(&path)?;
        println!("{} bytes", text.len());
    
        {
            let file = File::options().append(true).open(&path)?;
            let mut writer = BufWriter::new(file);
            writeln!(writer, "third line")?;
            writer.flush()?;
        } // the file is closed here
    
        let reader = BufReader::new(File::open(&path)?);
        for (number, line) in reader.lines().enumerate() {
            println!("{}: {}", number + 1, line?);
        }
    
        fs::remove_file(&path)?;
        match fs::read_to_string(&path) {
            Ok(_) => println!("still there"),
            Err(error) if error.kind() == io::ErrorKind::NotFound => println!("gone"),
            Err(error) => return Err(error),
        }
        Ok(())
    }

    Output

    23 bytes
    1: first line
    2: second line
    3: third line
    gone

    A file is closed when its File value is dropped, at the end of its scope; there’s no using or close() to forget. A missing file is an ordinary Err whose kind() you can match on. read_to_string also fails if the file isn’t valid UTF-8; use fs::read for raw bytes.

    When to use what: fs::read_to_string and fs::write for small files; BufReader and BufWriter for large files or many small writes; tokio::fs inside async code, so the runtime’s threads aren’t blocked.

    Learn more: Result and the ? operator, Drop & smart pointers, Async, futures & Tokio

    How do I read and write JSON?

    Use the serde and serde_json crates. Derive Serialize and Deserialize on a struct, then call serde_json::to_string and serde_json::from_str. JSON that doesn’t match the struct comes back as an Err, never as a half-filled value.

    use serde::{Deserialize, Serialize};
    use serde_json::json;
    
    #[derive(Debug, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    struct User {
        user_id: u32,
        display_name: String,
        #[serde(default)]
        tags: Vec<String>,
    }
    
    fn main() -> Result<(), serde_json::Error> {
        let user: User = serde_json::from_str(r#"{"userId":1,"displayName":"Ada"}"#)?;
        println!("{user:?}");
        println!("{}", serde_json::to_string(&user)?);
    
        if let Err(error) = serde_json::from_str::<User>(r#"{"userId":"one"}"#) {
            println!("rejected: {error}");
        }
    
        // JSON whose shape you don't know in advance
        let value = json!({ "name": "Grace", "languages": ["COBOL"] });
        println!("{}", value["languages"][0]);
        Ok(())
    }

    Output

    User { user_id: 1, display_name: "Ada", tags: [] }
    {"userId":1,"displayName":"Ada","tags":[]}
    rejected: invalid type: string "one", expected u32 at line 1 column 15
    "COBOL"

    rename_all = "camelCase" maps the Rust field names to the JSON keys, #[serde(default)] fills a missing key with an empty value, and an Option<T> field makes a key optional. Unlike JSON.parse with a type assertion, from_str checks every field’s type, like a schema validator generated from the struct.serde writes the conversion code at compile time, like the System.Text.Json source generator; there’s no reflection at all. Unlike System.Text.Json’s default, a missing non-Option field is an error.

    When to use what: a derived struct for JSON with a known shape; serde_json::Value and json! for arbitrary JSON; to_string_pretty for indented output.

    Learn more: Macros & serde

    How do I make HTTP requests?

    The standard library has no HTTP client. Most projects use the reqwest crate, which is async and runs on Tokio; its json feature deserializes responses with serde. (The examples on this site can’t download crates beyond a fixed set, so this block isn’t run.)

    cargo add reqwest --features json
    cargo add tokio --features full
    cargo add serde --features derive
    
    use serde::Deserialize;
    
    #[derive(Debug, Deserialize)]
    struct Todo {
        id: u32,
        title: String,
        completed: bool,
    }
    
    #[tokio::main]
    async fn main() -> Result<(), reqwest::Error> {
        let client = reqwest::Client::new();
        let todo: Todo = client
            .get("https://api.example.com/todos/1")
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?;
        println!("{todo:?}");
        Ok(())
    }

    .await goes after each step, so the chain reads left to right. A 404 or 500 response is still a successful send(); error_for_status() turns it into an Err, like checking response.ok after fetchlike EnsureSuccessStatusCode(). A Client holds a connection pool, so create one and reuse it, as you would a single HttpClient.

    When to use what: reqwest::Client in async code; reqwest::get(url) for a one-off request; the blocking feature (reqwest::blocking::get) in a small program that doesn’t use async.

    Learn more: Async, futures & Tokio, Macros & serde, Crates, workspaces & features

    How do I build an HTTP server or web API?

    Use a web framework crate. axum, from the Tokio project, is a common choice: a handler is an async function, its parameters (called extractors, such as Path, Query, Json and State) pull data out of the request, and its return value becomes the response. (This block isn’t run either.)

    cargo add axum
    cargo add tokio --features full
    cargo add serde --features derive
    
    use axum::{Json, Router, extract::Path, routing::get};
    use serde::Serialize;
    
    #[derive(Serialize)]
    struct User {
        id: u32,
        name: String,
    }
    
    async fn get_user(Path(id): Path<u32>) -> Json<User> {
        Json(User {
            id,
            name: format!("user {id}"),
        })
    }
    
    #[tokio::main]
    async fn main() -> std::io::Result<()> {
        let app = Router::new().route("/users/{id}", get(get_user));
        let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
        axum::serve(listener, app).await
    }

    GET /users/7 responds with user 7 as JSON. A path that isn’t a number is rejected with a 400 response before your handler runs, because Path<u32> can’t be extracted. It’s the same shape as an Express routea minimal API's app.MapGet, with the parsing declared in the handler’s types. (Path parameters are written {id} since axum 0.8; older versions used :id.)

    When to use what: axum for APIs and web apps; Router::with_state and a State<Arc<AppState>> extractor for shared dependencies such as a database pool; tower-http for middleware such as CORS, compression and tracing.

    Learn more: Async, futures & Tokio, Send & Sync, Macros & serde

    How do I use async/await?

    Write async fn, and put .await after the call. Two differences from TypeScriptC#: a future is lazy, so nothing runs until it’s awaited, and the standard library has no runtime, so you add one (almost always Tokio) and start it with #[tokio::main]. tokio::join! waits for several futures at once.

    TypeScript
    dashboard.ts
    import { setTimeout as sleep } from "node:timers/promises";
    
    async function load(name: string, ms: number): Promise<string> {
      await sleep(ms);
      return `${name} loaded`;
    }
    
    const [user, orders] = await Promise.all([load("user", 20), load("orders", 10)]);
    console.log(user);
    console.log(orders);
    C#
    Dashboard.cs
    var results = await Task.WhenAll(Load("user", 20), Load("orders", 10));
    Console.WriteLine(results[0]);
    Console.WriteLine(results[1]);
    
    static async Task<string> Load(string name, int ms)
    {
        await Task.Delay(ms);
        return $"{name} loaded";
    }
    Rust
    use std::time::Duration;
    use tokio::time::sleep;
    
    async fn load(name: &str, ms: u64) -> String {
        sleep(Duration::from_millis(ms)).await;
        format!("{name} loaded")
    }
    
    #[tokio::main]
    async fn main() {
        let (user, orders) = tokio::join!(load("user", 20), load("orders", 10));
        println!("{user}");
        println!("{orders}");
    }

    Output

    user loaded
    orders loaded

    Inside async code, use the async versions of anything that waits (tokio::time::sleep, tokio::fs, tokio::net): a blocking call holds up every task sharing that thread. Errors work as everywhere else: return a Result and use ?.

    When to use what: .await one at a time when each step needs the last one’s result; tokio::join! for a fixed set of futures; tokio::spawn for background work; plain threads, not async, for CPU-heavy work.

    Learn more: Async, futures & Tokio, Send & Sync

    How do I write unit tests?

    Mark a function #[test], put it in a #[cfg(test)] mod tests at the bottom of the file it tests, and run cargo test. There’s no framework to install; assertions are the assert!, assert_eq! and assert_ne! macros, and a test fails if it panics.

    pub fn slugify(title: &str) -> String {
        title
            .split_whitespace()
            .map(str::to_lowercase)
            .collect::<Vec<_>>()
            .join("-")
    }
    
    #[cfg(test)]
    mod tests {
        use super::*;
    
        #[test]
        fn joins_words_with_dashes() {
            assert_eq!(slugify("Hello Rust World"), "hello-rust-world");
        }
    
        #[test]
        fn ignores_extra_spaces() {
            assert_eq!(slugify("  Two   words "), "two-words");
        }
    }

    #[cfg(test)] leaves the module out of normal builds, and use super::* lets the tests reach private functions too. cargo test words runs only the tests whose names contain words. Tests in the tests/ folder test your public API from outside, and code examples in /// doc comments run as tests as well.

    When to use what: unit tests next to the code; integration tests in tests/; doc tests for examples in documentation; a fake that implements the same trait where you’d use a mock (see dependency injection).

    Learn more: Tests & doc tests

    Where did this go?

    Rust has no hidden this. A method names its receiver as its first parameter and always writes self.field. The form of that parameter says what the method does: &self reads, &mut self changes, and self takes ownership. A function in an impl block with no self is an associated function, Rust’s version of a static method, called with ::.

    struct Counter {
        count: u32,
    }
    
    impl Counter {
        fn new() -> Self {
            Self { count: 0 }
        }
    
        fn get(&self) -> u32 {
            self.count
        }
    
        fn increment(&mut self) {
            self.count += 1;
        }
    
        fn into_total(self) -> u32 {
            self.count
        }
    }
    
    let mut counter = Counter::new();
    counter.increment();
    counter.increment();
    println!("count: {}", counter.get());
    let total = counter.into_total(); // `counter` can't be used after this
    println!("total: {total}");

    Output

    count: 2
    total: 2

    Self with a capital S is the type the impl block is for; self is the value. There’s no rebinding either: a closure inside a method captures self like any other variable, so the arrow-function-versus-function question doesn’t exist.As in C#, counter.increment() passes counter as the receiver; Rust just makes the parameter visible and says whether it’s borrowed or moved.

    When to use what: &self for methods that read; &mut self for methods that change the value; self for methods that consume or convert it (into_…, build); no self for constructors such as new.

    Learn more: Structs & impl blocks

    Why can’t I return a reference to a local variable?

    Because the local is dropped when the function returns, and the reference would point at freed memory. In TypeScriptC#, the garbage collector keeps a returned object alive; in Rust, the compiler rejects the function instead:

    fn shout(name: &str) -> &str {
        let loud = name.to_uppercase();
        &loud
    }

    Rust doesn't compile this: error E0515

    error[E0515]: cannot return reference to local variable `loud`
     --> main.rs:3:5
      |
    3 |     &loud
      |     ^^^^^ returns a reference to data owned by the current function

    Return the owned value. That moves it to the caller, which is cheap: a String moves as its pointer, length and capacity, and the text isn’t copied. Returning a reference is fine when it borrows from a parameter, because the caller keeps the argument alive.

    fn shout(name: &str) -> String {
        name.to_uppercase()
    }
    
    fn first_word(text: &str) -> &str {
        text.split_whitespace().next().unwrap_or("")
    }
    
    println!("{}", shout("ada"));
    println!("{}", first_word("hello world"));

    Output

    ADA
    hello

    When to use what: return owned values (String, Vec<T>, your structs) from functions that create them; return &str or &T only when the result points into an argument.

    Learn more: Choosing parameter types, References: &T and &mut T, Lifetimes

    How do I clone an object graph?

    Add #[derive(Clone)] and call .clone(). It clones every field in turn, so owned data (String, Vec, nested structs) is copied deeply. The exception is Rc and Arc: cloning one adds an owner to the same value, so those parts stay shared.

    use std::rc::Rc;
    
    #[derive(Clone)]
    struct Team {
        members: Vec<String>,
        logo: Rc<String>,
    }
    
    let original = Team {
        members: vec![String::from("Ada")],
        logo: Rc::new(String::from("crab.png")),
    };
    let mut copy = original.clone();
    copy.members.push(String::from("Grace"));
    
    println!("original: {} member", original.members.len());
    println!("copy: {} members", copy.members.len());
    println!("same logo: {}", Rc::ptr_eq(&original.logo, &copy.logo));
    println!("logo owners: {}", Rc::strong_count(&original.logo));

    Output

    original: 1 member
    copy: 2 members
    same logo: true
    logo owners: 2

    A graph stored as indexes into a Vec (see graphs with cycles) clones deeply with a plain #[derive(Clone)], links included, because the links are just numbers. A graph built from Rc and RefCell needs a hand-written deep copy.

    When to use what: #[derive(Clone)] for a deep copy of owned data; Rc::clone (or Arc::clone) to share instead of copy; struct update syntax (..original.clone()) to copy with a few fields changed.

    Learn more: Copy vs. Clone, Shared ownership & interior mutability