Skip to content
binshelf/ rust

Search lessons

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

    Compare Rust with

    Lessons

    Module 1 · Fundamentals

    1.1Variables, mutability & shadowing

    Why Rust variables can't change unless you say so, how shadowing reuses a name, and when to use let, let mut, const or static.

    About 20 minutesBeginner

    On this page
    1. Concept map
    2. Immutable by default
    3. Immutable means the contents too
    4. Shadowing: the same name, a new variable
    5. const and static
    6. Which one should I use?
    7. Under the hood
    8. Common pitfalls
    9. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    A variable you never reassignconst total = 5const int total = 5 for compile-time constants only; no read-only local for other valueslet total = 5 (the default)
    A variable you changelet total = 5var total = 5let mut total = 5
    Changing the contents of a listAllowed even through constAllowed even through a readonly fieldNeeds let mut: immutability covers the contents too
    Declaring the same name againError in the same scope: cannot redeclare block-scoped variableError CS0128, or CS0136 in a nested scopeAllowed: shadowing makes a new variable, even of a different type
    A named constantconst MAX_RETRIES = 3 at module levelconst int MaxRetries = 3;const MAX_RETRIES: u32 = 3; (copied into every use)
    One global value for the whole programA module-level letA static fieldA static item: immutable unless it's thread-safe, such as an atomic or a Mutex

    In TypeScriptC#, a variable can change unless you mark it constconst or readonly. Rust flips that default: a variable can’t change unless you mark it mut. Rust also lets you declare the same name twice, and it has both const and static; its static doesn’t mean what TypeScript'sC#'s does. This lesson sorts all of that out, and ends with a table of which one to use.

    Immutable by default

    let declares a variable that can’t be reassigned. let mut declares one that can.

    TypeScript
    cart.ts
    const price = 20;
    let total = 0;
    total += price;
    total += price;
    console.log(`Total: ${total}`);
    C#
    Cart.cs
    const int price = 20; // works for a literal; C# has no read-only local for run-time values
    var total = 0;
    total += price;
    total += price;
    Console.WriteLine($"Total: {total}");
    Rust
    let price = 20;
    let mut total = 0;
    total += price;
    total += price;
    println!("Total: {total}");

    Output

    Total: 40

    Watch the keywords: Rust’s let is TypeScript’s const, and Rust’s let mut is TypeScript’s let.Rust’s let mut is C#‘s var. Plain let has no C# equivalent for run-time values: it’s a local you can never reassign. Leave out mut and assign anyway, and the compiler stops you, with a suggested fix:

    let total = 0;
    total += 20;
    println!("Total: {total}");

    Rust doesn't compile this: error E0384

    error[E0384]: cannot assign twice to immutable variable `total`
     --> main.rs:2:1
      |
    1 | let total = 0;
      |     ----- first assignment to `total`
    2 | total += 20;
      | ^^^^^^^^^^^ cannot assign twice to immutable variable
      |
    help: consider making this binding mutable
      |
    1 | let mut total = 0;
      |     +++

    Mental model shiftMutation is opt-in

    In TypeScriptC#, you have to remember to mark the things that shouldn’t change. In Rust, you mark the things that should. Most variables never change after they’re set, so most of your lets won’t need mut, and when you see mut you know to watch that variable.

    Immutable means the contents too

    TypeScript’s constC#‘s readonly only stops you pointing the name at something else. You can still change the object it points at. Rust’s let covers the whole value, contents included:

    TypeScript
    team.ts
    const names = ["Ada"];
    names.push("Grace"); // allowed: const only stops reassignment
    console.log(names.length);
    C#
    Team.cs
    var team = new Team();
    team.Names.Add("Grace"); // allowed: readonly only stops reassigning the field
    Console.WriteLine(team.Names.Count);
    
    class Team
    {
        public readonly List<string> Names = ["Ada"];
    }
    Rust
    let names = vec![String::from("Ada")];
    names.push(String::from("Grace"));
    println!("{}", names.len());

    Rust doesn't compile this: error E0596

    error[E0596]: cannot borrow `names` as mutable, as it is not declared as mutable
     --> team.rs:2:1
      |
    2 | names.push(String::from("Grace"));
      | ^^^^^ cannot borrow as mutable
      |
    help: consider changing this to be mutable
      |
    1 | let mut names = vec![String::from("Ada")];
      |     +++

    Adding to a vector changes it, and names isn’t mut, so Rust refuses. Write let mut names and it compiles. There’s no separate idea of a “read-only collection” to learn: if the variable isn’t mut, the value it owns can’t change through it, contents included. (Two exceptions come later: a variable that holds a &mut borrow of something else, and types built for shared changes, such as the atomic counter below.)

    Shadowing: the same name, a new variable

    You can declare a variable with the same name as one already in scope. The new one shadows the old one: from that line on, the name means the new variable. It’s most useful when you turn a value into another form step by step:

    TypeScript
    quantity.ts
    const input = " 42 ";
    const trimmed = input.trim();
    const quantity = Number(trimmed);
    console.log(quantity * 2);
    C#
    Quantity.cs
    var input = " 42 ";
    var trimmed = input.Trim();
    var quantity = int.Parse(trimmed);
    Console.WriteLine(quantity * 2);
    Rust
    let quantity = " 42 ";
    let quantity = quantity.trim();
    let quantity: i32 = quantity.parse().expect("quantity should be a number");
    println!("{}", quantity * 2);

    Output

    84

    TypeScriptC# needs three names, because redeclaring a variable in the same scope is an error. Rust lets you reuse quantity, so the names that are only steps on the way don’t clutter the rest of the function. Each let creates a new variable, so the type can change: the first two are string slices (&str) and the last is an i32. .expect stops the program with that message if the text isn’t a number, where TypeScript’s Number would quietly return NaN, much like int.Parse throwing in C#; Module 6 covers handling errors properly.

    Shadowing is not the same as mut:

    • let mut lets you change one variable. Its type stays fixed.
    • Shadowing declares a new variable with the same name. It can have a different type, and neither variable has to be mut.

    Assigning a value of another type to a mut variable fails:

    let mut quantity = " 42 ";
    quantity = quantity.trim().len();
    println!("{quantity}");

    Rust doesn't compile this: error E0308

    error[E0308]: mismatched types
     --> main.rs:2:12
      |
    1 | let mut quantity = " 42 ";
      |                    ------ expected due to this value
    2 | quantity = quantity.trim().len();
      |            ^^^^^^^^^^^^^^^^^^^^^ expected `&str`, found `usize`

    const and static

    Both declare a named value that lives outside any one function call, so you can put them at the top of a file. Both need a type, and by convention both use SCREAMING_SNAKE_CASE. They differ in what the compiler does with them.

    • const is a value with a name. The compiler copies it into every place you use it, like a literal you typed there. It’s the equivalent of C#‘s const.A module-level const is the closest thing in TypeScript, but there it’s still a variable that exists at run time.
    • static is one value at one fixed memory address, which exists for the whole time the program runs. Every use refers to that same place.

    Here’s a retry limit (a constant) and a request counter (one shared value the program updates):

    TypeScript
    api.ts
    const MAX_RETRIES = 3;
    let requestCount = 0;
    
    function sendRequest(): void {
      requestCount += 1;
    }
    
    sendRequest();
    sendRequest();
    console.log(`${requestCount} requests, max ${MAX_RETRIES} retries`);
    C#
    Api.cs
    Api.SendRequest();
    Api.SendRequest();
    Console.WriteLine($"{Api.RequestCount} requests, max {Api.MaxRetries} retries");
    
    static class Api
    {
        public const int MaxRetries = 3;
        public static int RequestCount;
    
        public static void SendRequest() => RequestCount++;
    }
    Rust
    use std::sync::atomic::{AtomicU32, Ordering};
    
    const MAX_RETRIES: u32 = 3;
    static REQUEST_COUNT: AtomicU32 = AtomicU32::new(0);
    
    fn send_request() {
        REQUEST_COUNT.fetch_add(1, Ordering::Relaxed);
    }
    
    fn main() {
        send_request();
        send_request();
        let count = REQUEST_COUNT.load(Ordering::Relaxed);
        println!("{count} requests, max {MAX_RETRIES} retries");
    }

    Output

    2 requests, max 3 retries

    Why not a plain number for the counter? Any thread can reach a static, so if two threads could change a plain number at once, that would be a data race. Rust therefore makes static values immutable. To update one, you use a type that’s safe to change from several threads: an atomic integer like AtomicU32, or a Mutex. fetch_add adds 1 in a single step that no other thread can interrupt, and Ordering::Relaxed is enough for a simple counter. Module 12 covers atomics and Mutex.

    Common pitfallRust's static isn't a class's static

    In TypeScript, static means “belongs to the class, not to an instance”: static methods and static properties.In C#, static means “belongs to the type, not to an instance”: static methods, static fields, static classes. Rust has no classes, and its static means only “one value at a fixed address for the whole program”. The ideas you know map elsewhere:

    • A static method such as User.create() is an associated function in Rust, called as User::create(). See Structs & impl blocks.
    • A static readonly property is usually a Rust const, or a static if it needs to be built when the program runs (see the table below).
    • A mutable static property is a static holding an atomic or a Mutex, and in Rust it’s rarely the best design.
    • A static method such as User.Create() is an associated function in Rust, called as User::create(). See Structs & impl blocks.
    • A const field is a Rust const.
    • A static readonly field is usually a Rust const, or a static if it needs to be built when the program runs (see the table below).
    • A mutable static field is a static holding an atomic or a Mutex, and in Rust it’s rarely the best design.

    You’ll also see 'static, with an apostrophe. That’s a lifetime, a different thing again; Reading Rust’s symbols explains it.

    Which one should I use?

    WhatWhenWhyHow
    letEvery variable, by default.Most values never change after they’re set. The compiler enforces it, and anyone reading the code knows the value stays the same.let total = 0; The type is usually inferred.
    let mutThe variable really changes: a counter, an accumulator, a collection you add to.It marks exactly what can change. The compiler warns if you add mut and never change the variable.let mut total = 0; then total += 1;
    ShadowingYou turn a value into a new form (trim it, parse it, unwrap it) and won’t need the old form again.No throwaway names like input and trimmed, and the type can change. Neither variable needs mut.let quantity = quantity.trim();
    constAny fixed value you want to name: limits, sizes, default settings. This covers almost every “global”.There’s no variable to look up at run time: the value is built into each use. It can go in any scope.const MAX_RETRIES: u32 = 3; The type is required.
    staticYou need one shared instance at a fixed address: a global counter or cache, or a large table you don’t want copied into every use.Every use refers to the same memory, which lives until the program ends.static COUNT: AtomicU32 = AtomicU32::new(0); For a value built at run time, use static CONFIG: LazyLock<Config> = LazyLock::new(load_config);

    Rule of thumb: write let, and add mut only when the compiler tells you or you know the value will change. Use shadowing to give each step of a conversion the same name. For named values outside functions, use const; reach for static only when you need one shared, changeable thing, and even then, passing the value to the functions that need it is usually the better design. Never use static mut.

    The same decision as questions, asked in order; stop at the first yes:

    let, let mut, shadowing, const or static?
    1. Does the whole program need one shared instance at a fixed address, such as a global counter, a cache or a large table?

      Yes

      staticHold an atomic or a Mutex to change it, or a LazyLock to build it at run time. Passing the value to the functions that need it is often the better design.

      No
    2. Is it a fixed value you want to name, known when you write the code: a limit, a size, a default?

      Yes

      constThe type is required: const MAX_RETRIES: u32 = 3;

      No
    3. Are you turning a value into a new form, and won't need the old form again?

      Yes

      Shadow it: let again with the same nameThe type can change, and neither variable needs mut.

      No
    4. Will the variable change after it's set?

      Yes

      let mut

      No
    5. Otherwise: let

    Under the hood

    let and let mut produce the same machine code. Mutability is a permission the compiler checks, not something stored at run time.

    Shadowing doesn’t overwrite or free the old variable either. It only hides its name. The old value stays alive until the end of the scope, which is why this works: the second name borrows part of the first one, so the first String must still exist.

    let name = String::from("  Ada  ");
    let name = name.trim();
    println!("[{name}]");
    After let name = name.trim()There are two variables called name on the stack. The first, a String, holds a pointer to a heap buffer of 7 bytes (two spaces, A, d, a, two spaces), a length of 7 and a capacity of 7. The second, a &str, points at index 2 of the same buffer with a length of 3, so it views just Ada. The first name is hidden by the second but still owns the buffer, and both are dropped at the end of the scope.StackHeapname (1st, hidden): Stringptrlen7capacity7name (2nd): &strptrlen3heap buffer␣␣Ada␣␣
    After let name = name.trim(). There are two variables called name on the stack. The first, a String, holds a pointer to a heap buffer of 7 bytes (two spaces, A, d, a, two spaces), a length of 7 and a capacity of 7. The second, a &str, points at index 2 of the same buffer with a length of 3, so it views just Ada. The first name is hidden by the second but still owns the buffer, and both are dropped at the end of the scope.

    const and static differ in where the value lives:

    • A const has no address of its own. Each use becomes a copy of the value in the compiled code, as if you’d typed the literal there. (C# does the same with const: it even copies the value into other assemblies that use it.)(A TypeScript const is different: it’s still a variable the program reads at run time.)
    • A static is stored once in the executable’s data section. Every use reads or writes that one place. Its value is never dropped: it lives until the program exits.

    Both are set at compile time, so their initializers can only call const fn functions. There’s no equivalent of a module's top-level code running when it's first importeda C# static constructor running on first use. This fails, because String::from allocates memory on the heap, which can only happen while the program runs:

    static GREETING: String = String::from("hello");
    println!("{GREETING}");

    Rust doesn't compile this: error E0015

    error[E0015]: cannot call non-const associated function `<String as From<&str>>::from` in statics
     --> main.rs:1:27
      |
    1 | static GREETING: String = String::from("hello");
      |                           ^^^^^^^^^^^^^^^^^^^^^
      |
      = note: calls in statics are limited to constant functions, tuple structs and tuple variants
      = note: consider wrapping this expression in `std::sync::LazyLock::new(|| ...)`

    For a string, const GREETING: &str = "hello"; is the fix. For a value that really has to be built at run time, such as a config file you load, wrap it in std::sync::LazyLock, which runs the code the first time the value is used.

    Common pitfalls

    Common pitfallRust's let can't change

    The same word means opposite things. TypeScript’s let can change; Rust’s let can’t. TypeScript’s const is Rust’s let, and Rust’s const is a compile-time constant. When you translate code, map TypeScript let to let mut and const to let.
    Rust’s let looks like C#‘s var, but it can’t change. Rust’s const is a compile-time constant, like C#‘s const. When you translate code, map var to let mut if the variable changes and to let if it doesn’t.

    Common pitfallShadowing inside a block doesn't change the outer variable

    A let inside a block makes a new variable that ends with the block. Code after the block sees the outer one again:

    let level = 1;
    {
        let level = level + 1;
        println!("inside: {level}");
    }
    println!("after: {level}");

    This prints inside: 2, then after: 1. If you meant to update level, declare it let mut level and assign without let: level += 1;. (TypeScript reports an error for this code, because the inner level is used before it’s declared.C# reports CS0136 for this code. Rust allows it, so look out for a stray let.)

    Common pitfallstatic mut needs unsafe

    Coming from TypeScriptC#, a static mut counter looks like the obvious translation of a module-level let or a static propertya static field. Rust won’t let you touch it outside an unsafe block, because nothing stops two threads changing it at once:

    static mut COUNT: u32 = 0;
    COUNT += 1;

    Rust doesn't compile this: error E0133

    error[E0133]: use of mutable static is unsafe and requires unsafe block
     --> main.rs:2:1
      |
    2 | COUNT += 1;
      | ^^^^^ use of mutable static
      |
      = note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior

    Don’t reach for unsafe to fix it. Use an atomic or a Mutex in a plain static, as shown above, or better, pass the counter to the code that needs it.

    Try it yourself

    Exercise: port this to Rust

    Port this program to Rust. Use a const for the tax rate, shadowing to turn the price text into a number, and mut only where a value really changes.

    Starting code in TypeScript
    tax.ts
    const TAX_RATE_PERCENT = 20;
    const input = "50";
    const price = Number(input);
    let total = price;
    total += (price * TAX_RATE_PERCENT) / 100;
    console.log(`Total: ${total}`);
    Starting code in C#
    Tax.cs
    const int TaxRatePercent = 20;
    var input = "50";
    var price = int.Parse(input);
    var total = price;
    total += price * TaxRatePercent / 100;
    Console.WriteLine($"Total: {total}");

    Expected output

    Total: 60
    Show a hint

    Put the tax rate in a const with a u32 type. Parse the price with a shadowing let and an explicit u32 type. Only total changes after it's set, so it's the only variable that needs mut.

    Show a solution
    const TAX_RATE_PERCENT: u32 = 20;
    
    fn main() {
        let price = "50";
        let price: u32 = price.parse().expect("price should be a number");
        let mut total = price;
        total += price * TAX_RATE_PERCENT / 100;
        println!("Total: {total}");
    }

    TAX_RATE_PERCENT is a const because it never changes and needs no address. price is shadowed, turning the text into a number under the same name, and neither price needs mut. total is the one variable that changes, so it's let mut.