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.
On this page
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| A variable you never reassign | const total = 5 | const int total = 5 for compile-time constants only; no read-only local for other values | let total = 5 (the default) |
| A variable you change | let total = 5 | var total = 5 | let mut total = 5 |
| Changing the contents of a list | Allowed even through const | Allowed even through a readonly field | Needs let mut: immutability covers the contents too |
| Declaring the same name again | Error in the same scope: cannot redeclare block-scoped variable | Error CS0128, or CS0136 in a nested scope | Allowed: shadowing makes a new variable, even of a different type |
| A named constant | const MAX_RETRIES = 3 at module level | const int MaxRetries = 3; | const MAX_RETRIES: u32 = 3; (copied into every use) |
| One global value for the whole program | A module-level let | A static field | A 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.
const price = 20;
let total = 0;
total += price;
total += price;
console.log(`Total: ${total}`);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}");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:
const names = ["Ada"];
names.push("Grace"); // allowed: const only stops reassignment
console.log(names.length);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"];
}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:
const input = " 42 ";
const trimmed = input.trim();
const quantity = Number(trimmed);
console.log(quantity * 2);var input = " 42 ";
var trimmed = input.Trim();
var quantity = int.Parse(trimmed);
Console.WriteLine(quantity * 2);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 mutlets 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.
constis 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#‘sconst.A module-levelconstis the closest thing in TypeScript, but there it’s still a variable that exists at run time.staticis 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):
const MAX_RETRIES = 3;
let requestCount = 0;
function sendRequest(): void {
requestCount += 1;
}
sendRequest();
sendRequest();
console.log(`${requestCount} requests, max ${MAX_RETRIES} retries`);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++;
}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 asUser::create(). See Structs & impl blocks. - A
static readonlyproperty is usually a Rustconst, or astaticif it needs to be built when the program runs (see the table below). - A mutable static property is a
staticholding an atomic or aMutex, and in Rust it’s rarely the best design.
- A static method such as
User.Create()is an associated function in Rust, called asUser::create(). See Structs & impl blocks. - A
constfield is a Rustconst. - A
static readonlyfield is usually a Rustconst, or astaticif it needs to be built when the program runs (see the table below). - A mutable static field is a
staticholding an atomic or aMutex, 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?
| What | When | Why | How |
|---|---|---|---|
let | Every 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 mut | The 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; |
| Shadowing | You 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(); |
const | Any 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. |
static | You 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:
Does the whole program need one shared instance at a fixed address, such as a global counter, a cache or a large table?
YesNostaticHold an atomic or aMutexto change it, or aLazyLockto build it at run time. Passing the value to the functions that need it is often the better design.Is it a fixed value you want to name, known when you write the code: a limit, a size, a default?
YesNoconstThe type is required:const MAX_RETRIES: u32 = 3;Are you turning a value into a new form, and won't need the old form again?
YesNoShadow it:
letagain with the same nameThe type can change, and neither variable needsmut.Will the variable change after it's set?
YesNolet mutOtherwise:
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}]");const and static differ in where the value lives:
- A
consthas 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 withconst: it even copies the value into other assemblies that use it.)(A TypeScriptconstis different: it’s still a variable the program reads at run time.) - A
staticis 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
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.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.
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}`);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.
Saved in this browser only.