Hello World in Mojo
Your first Mojo program - the classic Hello World example with Docker setup
Mojo brings Python’s familiar syntax to systems-level programming. If you know Python, you already know how to write Hello World in Mojo—with one small addition.
The Code
Create a file named hello.mojo:
def main():
print("Hello, World!")
Understanding the Code
def main()- The entry point of every Mojo program. Unlike Python scripts, Mojo requires an explicitmain()function as the program entry point.print()- A built-in function that outputs text to the console, just like Python."Hello, World!"- A string literal enclosed in double quotes.- Indentation - Like Python, Mojo uses whitespace indentation to define code blocks.
Why main() Is Required
In Python, code at the top level of a file runs automatically. Mojo requires a main() function because it’s a compiled language—the compiler needs a defined entry point, similar to C, Rust, or Java. This is one of the few differences you’ll notice coming from Python.
Running with Docker
The easiest way to run this without installing Mojo locally:
| |
Running Locally
If you have Mojo installed via Pixi:
| |
Expected Output
Hello, World!
def vs fn: Two Kinds of Functions
Mojo offers two ways to define functions:
# Dynamic style (Python-compatible)
def greet(name):
print("Hello, " + name + "!")
# Strict style (full type safety)
fn greet_strict(name: String):
print("Hello, " + name + "!")
def- Flexible, dynamically typed, works like Pythonfn- Strict, requires type annotations, catches more errors at compile time
For Hello World, def is the simplest choice. As your programs grow, fn provides stronger guarantees.
Key Concepts
- Mojo is compiled - Source code (
.mojo) is compiled to native machine code via MLIR, no interpreter needed main()is required - Every executable Mojo program needs amain()function- Python syntax -
print(), indentation, and basic syntax work just like Python - Two function styles -
deffor flexibility,fnfor strict type safety - High performance - Even this simple program compiles to optimized native code
Compiling to a Binary
One advantage over Python: you can compile Mojo programs to standalone executables:
| |
The resulting binary is small and runs without any runtime or interpreter.
Next Steps
Now that you’ve run your first Mojo program, you’re ready to explore what makes Mojo special—its ability to combine Python’s ease with C++-level performance. Continue to learn about variables, types, and Mojo’s powerful type system.
Running Today
All examples can be run using Docker:
docker pull codearchaeology/mojo:latest