Mojo Variables and Constants

Variables and constants are named containers that hold data in your program. A variable can hold different values over time, while a constant holds one value forever. Mojo gives you precise control over both, which helps the compiler generate faster code.

The Box Analogy

Variables                    Constants
┌──────────────────┐         ┌──────────────────┐
│   Box with lid   │         │   Sealed box     │
│                  │         │                  │
│   score = 10     │         │   PI = 3.14159   │
│   ↓              │         │   (never changes)│
│   score = 20     │         │                  │
│   ↓              │         │   Lock applied   │
│   score = 35     │         │   at creation    │
└──────────────────┘         └──────────────────┘
  Can replace the           Cannot replace the
  value inside              value inside

Declaring Variables with var

Use the var keyword to create a variable. You can assign a value right away or assign it later.

fn main():
    var score = 10
    print(score)   # Prints: 10

    score = 20     # Reassign the variable
    print(score)   # Prints: 20

The keyword var tells Mojo to reserve a named slot in memory. The equals sign places a value into that slot. You can replace that value as many times as you need.

Declaring Without an Initial Value

You can declare a variable first and assign a value later. You must provide a type when you do this, because Mojo cannot guess the type without seeing a value.

fn main():
    var temperature: Float64
    temperature = 36.6
    print(temperature)  # Prints: 36.6

Declaring Constants with let

Use let to create a constant. Once you set its value, it never changes. Trying to change it causes a compile-time error, which means Mojo catches the mistake before the program even runs.

fn main():
    let gravity = 9.81
    print(gravity)   # Prints: 9.81

    # gravity = 10.0  ← This would cause a compile error

Constants communicate intent. When another developer reads your code, a let variable signals "this value is fixed by design, do not modify it."

Type Inference vs Explicit Types

Mojo can deduce the type of a variable from the value you assign. This is called type inference. You can also state the type explicitly after a colon.

fn main():
    # Type inference — Mojo figures out the type
    var apples = 5        # Mojo infers Int
    var price = 1.99      # Mojo infers Float64
    var name = "Mango"    # Mojo infers String

    # Explicit types — you state the type yourself
    var count: Int = 5
    var ratio: Float64 = 1.99
    var fruit: String = "Mango"

Both styles produce the same result. Explicit types make code easier to read in large projects. Inferred types keep short scripts concise.

Diagram: Type Inference in Action

  Code You Write         What Mojo Sees
  ────────────────       ──────────────────────────
  var x = 42        →   var x: Int = 42
  var y = 3.14      →   var y: Float64 = 3.14
  var z = "Hi"      →   var z: String = "Hi"
  var b = True      →   var b: Bool = True

Mojo's Basic Types at a Glance

Int

Stores whole numbers with no decimal point. Examples: -5, 0, 100. In Mojo, Int is platform-dependent (64-bit on 64-bit systems).

Float64

Stores numbers with decimal points. Examples: 3.14, -0.001, 2.0. The 64 refers to the 64 bits used to store the number, giving it about 15 significant digits of precision.

Bool

Stores either True or False. Useful for conditions and flags.

String

Stores text. Always enclose string values in double quotes.

Variable Scope

Scope defines where a variable is visible and usable. A variable declared inside a function only exists inside that function. Code outside cannot see it.

fn greet():
    var message = "Hello!"
    print(message)   # Works fine

fn main():
    greet()
    # print(message)  ← Error: 'message' is not in scope here
Scope Diagram:

┌─── greet() scope ────────────────┐
│  var message = "Hello!"          │
│  print(message)  ✓               │
└──────────────────────────────────┘

┌─── main() scope ─────────────────┐
│  greet()                         │
│  print(message)  ✗ (not visible) │
└──────────────────────────────────┘

Swapping Variable Values

A common programming task swaps the values of two variables. Many beginners accidentally overwrite one value. Use a temporary variable to do it correctly.

fn main():
    var a = 10
    var b = 20

    # Without temp — WRONG approach
    # a = b  ← loses original value of a!

    # Correct approach using a temp variable
    var temp = a
    a = b
    b = temp

    print(a)  # Prints: 20
    print(b)  # Prints: 10
Swap Step-by-Step:

  Start:   a=10  b=20
  temp=a   a=10  b=20  temp=10
  a=b      a=20  b=20  temp=10
  b=temp   a=20  b=10  temp=10
  Done:    a=20  b=10  ✓

Naming Variables Well

Good variable names make code readable. Follow these habits:

Use lowercase letters and underscores to separate words: total_score, user_age, item_count. Avoid single-letter names except in short math loops where convention allows i, j, or x. Never use reserved words like fn, var, let, or if as variable names — Mojo will refuse to compile.

Key Takeaways

Use var for data that changes and let for data that stays fixed. Mojo infers types automatically or you can declare them explicitly after a colon. Variables exist only inside the scope where you declared them. Meaningful variable names make your code far easier to read and maintain.

Leave a Comment

Your email address will not be published. Required fields are marked *