Mojo vs Rust & C++
Rust and C++ are the languages people reach for when code has to be fast. Mojo wants to play in the same league, but with Python’s syntax. It takes some ideas straight from Rust, keeps C++’s “you’re in control” attitude, and changes a few things on purpose.
You don’t need to know Rust or C++ to read this page. The code snippets are short, and every one of them was compiled and run (Rust 1.97, g++ 13, Mojo 1.2).
The same task in three languages
Section titled “The same task in three languages”A function that adds up a list of numbers, without copying the list. First Rust:
fn total(numbers: &Vec<i64>) -> i64 { let mut sum = 0; for n in numbers { sum += n; } sum}
fn main() { let nums = vec![3, 4, 5]; println!("{}", total(&nums)); println!("{}", nums.len());}Then C++:
#include <iostream>#include <vector>
long total(const std::vector<long>& numbers) { long sum = 0; for (long n : numbers) { sum += n; } return sum;}
int main() { std::vector<long> nums = {3, 4, 5}; std::cout << total(nums) << "\n"; std::cout << nums.size() << "\n";}And Mojo:
def total(numbers: List[Int]) -> Int: var sum = 0 for n in numbers: sum += n return sum
def main(): var nums: List[Int] = [3, 4, 5] print(total(nums)) print(len(nums))Output (the same for all three):
123Look at how each one says “read this list, don’t copy it”:
- Rust writes
&twice: in the type (&Vec<i64>) and at the call (total(&nums)). - C++ writes
const std::vector<long>&. Leave out the&and C++ quietly copies the whole vector. - Mojo writes nothing. A plain argument is a read-only reference by default. You only add a keyword when you want something else, like
mutto change the caller’s value.
What Mojo shares with Rust: ownership
Section titled “What Mojo shares with Rust: ownership”Mojo, like Rust, has no garbage collector. Instead, every value has one owner, and the compiler tracks who owns what. When the owner is done, the value is cleaned up. The Mojo manual’s ownership page describes the rules; here’s how they look in practice.
Moving a value
Section titled “Moving a value”You can hand a value to a function for good with the ^ (transfer) operator. After that, the old variable can’t be used:
def take(var xs: List[Int]): print("took", xs)
def main(): var a: List[Int] = [1, 2, 3] take(a^) print(a)hello.mojo:7:10: error: use of uninitialized value 'a' print(a) ^hello.mojo:5:9: note: 'a' declared here var a: List[Int] = [1, 2, 3] ^mojo: error: failed to run the pass managerRust reports the same mistake as error[E0382]: borrow of moved value: 'a'. The idea is identical: once moved, the value belongs to someone else. The difference is when a move happens. In Rust, passing a Vec by value moves it automatically. In Mojo you write ^ to move, or .copy() to copy, and if you write neither for a type like List, the compiler asks you to pick.
No changing what someone else is reading
Section titled “No changing what someone else is reading”Rust won’t let you hold a mutable reference and another reference to the same value at once. Mojo has a similar rule, called argument exclusivity:
def append_twice(mut s: String, other: String): s += other s += other
def main(): var s = String("o") append_twice(s, s) print(s)hello.mojo:7:17: error: aliasing values passed mutably to 's' argument and passed immutably to 'other' argument in 'append_twice' call append_twice(s, s) ^~ ~mojo: error: failed to parse the provided Mojo source moduleIf s and other were the same string, the function would be changing the text it’s reading from. Mojo refuses, just as Rust would. The fix is to pass a copy as the second argument.
Lifetimes and origins
Section titled “Lifetimes and origins”Rust uses lifetimes to check that a reference never outlives the value it points to. Mojo has the same safety goal and calls its version origins. For everyday code you rarely write them by hand in either language. You’ll meet them in Mojo References & Origins.
Where Mojo differs from Rust
Section titled “Where Mojo differs from Rust”Values are destroyed as soon as possible
Section titled “Values are destroyed as soon as possible”Rust drops a value at the end of its scope (usually the closing }). Mojo destroys a value right after its last use. This program shows it. __deinit__ is a special method Mojo calls when a value is destroyed:
struct Noisy: var name: String
def __init__(out self, name: String): self.name = name print("created", name)
def __deinit__(deinit self): print("destroyed", self.name)
def main(): var a = Noisy("a") var b = Noisy("b") print("using", a.name) print("using", b.name) print("end of main")Output:
created acreated busing adestroyed ausing bdestroyed bend of maina is destroyed straight after its last use, before b is even used, and both are gone before end of main. In Rust or C++, both would live until the end of main. Mojo calls this ASAP destruction, and the manual’s page on automatic destruction explains the details. Mostly you won’t notice it; it matters when you write your own cleanup code.
Other differences from Rust
Section titled “Other differences from Rust”- Errors. Rust returns a
Resultand you pass errors up with?. Mojo usesraises,raiseandtry/except, which look like Python. Under the hood, a Mojo error is returned as a value too, not thrown like a C++ exception. - Integer overflow. We tested
i64::MAX + 1in Rust: a normal (debug) build panics withattempt to add with overflow, an optimized build wraps around. Mojo’sIntwraps silently in both cases (you get-9223372036854775808). - Syntax. Rust has its own syntax with braces,
let,fnandmatch. Mojo looks like Python. - Maturity. Rust reached 1.0 in 2015 and has a huge package registry (crates.io). Mojo reached 1.0 in 2026, and its ecosystem is still small. The Mojo roadmap still lists a package manager as future work.
Where Mojo differs from C++
Section titled “Where Mojo differs from C++”- Memory safety. In C++ nothing stops you from using a value after it’s been freed. Mojo’s ownership checks catch those mistakes in normal code. Like C++, Mojo still has raw pointers (
UnsafePointer) when you need them, and then the safety is up to you. See Mojo Unsafe Pointers. - Copies. C++ copies objects by default unless you ask for a reference. Mojo passes a read-only reference by default, and expensive types like
Listmust be copied explicitly with.copy(). - Generics. C++ uses templates (and, since C++20, concepts). Mojo uses parameters in square brackets and traits, and the compiler checks a generic function against its trait right away, not only when you call it with a real type. A taste:
trait Shape: def area(self) -> Float64: ...
@fieldwise_initstruct Square(Shape): var side: Float64
def area(self) -> Float64: return self.side * self.side
def print_area[T: Shape](s: T): print(s.area())
def main(): print_area(Square(3.0))Output:
9.0[T: Shape] means “any type T that conforms to the Shape trait”. It’s close to a Rust generic with a trait bound, or a C++ template with a concept. More in Mojo Generics and Mojo Traits.
- Overflow. Signed integer overflow in C++ is undefined behavior: the compiler is allowed to assume it never happens. Mojo defines it:
Intwraps. - Build setup. No header files, no separate build system to learn for small projects. You run
mojo build file.mojo. - Talking to C and C++. Mojo can call C libraries, and C++ only through functions declared
extern "C", according to the Mojo FAQ. See Mojo Calling C.
Side by side
Section titled “Side by side”| Mojo | Rust | C++ | |
|---|---|---|---|
| Looks like | Python | Its own (braces, let, fn) |
C (braces, semicolons) |
| 1.0 / first release | 2026 | 2015 | 1985 |
| Memory | Ownership, no garbage collector | Ownership and borrowing, no garbage collector | Manual, plus RAII and smart pointers |
| Pass an argument without copying | The default | &value |
const T& |
| When values are cleaned up | Right after last use | End of scope | End of scope |
| Errors | raises + try/except |
Result + ? |
Exceptions or error codes |
| Integer overflow | Wraps | Panics in debug builds, wraps in release | Undefined for signed integers |
| Generics | Parameters [T: Trait] |
Generics with trait bounds | Templates and concepts |
| GPU code | Built into the language and library | Through community projects | CUDA, HIP, SYCL and others |
| Uses Python libraries | Directly (Python.import_module) |
Through crates like PyO3 | Through tools like pybind11 |
| Runs on | Linux, macOS (Apple silicon), Windows through WSL | Nearly everywhere | Nearly everywhere |
| Ecosystem | Small and young | Large (crates.io) | Very large, but spread out |
Which one should you pick?
Section titled “Which one should you pick?”- Pick Rust for long-lived systems software, servers, command-line tools, embedded work, or anything that has to run on Windows natively. It’s mature and its tooling is excellent.
- Pick C++ when you work with existing C++ code, game engines, or libraries that only exist in C++.
- Pick Mojo when you come from Python, want fast CPU or GPU code for numbers and AI, and like the idea of one language for both the easy and the fast parts. Accept that it’s young: fewer libraries, fewer answers online, and some things still change between releases.
Practice
Section titled “Practice”1. Fix the move
Section titled “1. Fix the move”This program fails with use of uninitialized value 'names'. Make it print both lines, without removing the call to show.
def show(var items: List[String]): print(items)
def main(): var names: List[String] = ["Ann", "Bo"] show(names^) print(len(names))Hint: either keep your own copy, or let show read the list instead of owning it.
Show solution
def show(items: List[String]): print(items)
def main(): var names: List[String] = ["Ann", "Bo"] show(names) print(len(names))Output:
[Ann, Bo]2show only reads the list, so it doesn’t need to own it. With the default (read-only) argument and no ^, names stays with main. Passing names.copy()^ would also work, but copies for no reason.
2. Predict the order
Section titled “2. Predict the order”Without running it, write down the order of the lines this prints. Then run it and check.
struct Tag: var name: String
def __init__(out self, name: String): self.name = name
def __deinit__(deinit self): print("bye", self.name)
def main(): var x = Tag("x") var y = Tag("y") print("hi", y.name) print("hi", x.name) print("done")Hint: a value is destroyed right after its last use, not at the end of main.
Show solution
Output:
hi ybye yhi xbye xdoney is last used in the first print, so it goes first. x is last used in the second print. Both are gone before done. In Rust or C++, both would be dropped after done.
- Mojo passes arguments as read-only references by default, with no
&to write. - Like Rust, Mojo has ownership: one owner per value,
^to move, and an error if you use a moved value. - Mojo enforces argument exclusivity, similar to Rust’s borrowing rules.
- Mojo destroys values right after their last use; Rust and C++ wait for the end of the scope.
- Errors use
raisesandtry/except, notResultor C++ exceptions. Intwraps on overflow; Rust panics in debug builds, and C++ signed overflow is undefined.- Rust and C++ are far more mature; Mojo’s strengths are Python-style syntax, GPU support and Python interop.
Next up: Mojo Get Started, installing Mojo and running your first program.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo ownership: argument conventions, exclusivity and transfers, with a short comparison to C++ and Rust.
- Automatic destruction: how and when Mojo destroys values.
- Mojo roadmap: what’s finished, what’s coming, and Modular’s note that Mojo isn’t aiming to match Rust or C++ feature for feature.
- Mojo vision: the design goals behind Mojo.
- The Rust Programming Language, chapter 4: Rust’s ownership explained, useful if you want to compare the two.