Skip to content

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).

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):

12
3

Look 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 mut to change the caller’s value.

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.

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 manager

Rust 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.

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 module

If 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.

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.

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 a
created b
using a
destroyed a
using b
destroyed b
end of main

a 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.

  • Errors. Rust returns a Result and you pass errors up with ?. Mojo uses raises, raise and try/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 + 1 in Rust: a normal (debug) build panics with attempt to add with overflow, an optimized build wraps around. Mojo’s Int wraps silently in both cases (you get -9223372036854775808).
  • Syntax. Rust has its own syntax with braces, let, fn and match. 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.
  • 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 List must 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_init
struct 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: Int wraps.
  • 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.
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
  • 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.

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]
2

show 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.

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 y
bye y
hi x
bye x
done

y 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 raises and try/except, not Result or C++ exceptions.
  • Int wraps 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

1. How do you pass a list to a Mojo function so it can read it without copying?
2. When does Mojo destroy a value?
3. What happens after take(a^) if you then use a?
4. What does Mojo's Int do when it goes past its largest value?