This is a quick introduction to how to write code in Rust. Each example will be shown side-by-side with a rough Python equivalent. All of these examples can be copy-pasted into the Rust Playground.
Hello World
Python | Rust |
---|---|
|
|
Fibonacci
Python | Rust |
---|---|
|
|
In Rust, functions automatically return the last expression, so it’s possible to just write fib(n-1) + fib(n-2)
rather than return fib(n-1) + fib(n-2);
. Note the lack of a semicolon: semicolons are only for statements that you don’t want to return.
Rust also has several integer types, including usize
, isize
, u8
, i8
, u32
, i32
, u64
, and i64
. In general, usize
is the most common for integers.
Primes
Python | Rust |
---|---|
|
|
Just your regular ol’ for
and while
loops. Rust also has loop {}
, which works the same while true {}
. Note the mut n
: the keyword mut
means that a variable can be changed.
What time is it?
Python | Rust |
---|---|
|
|
Note that {:?}
is the “debug” formatter, and {}
is the “display” formatter. This means that {}
is usually prettier, but it’s not always available.
Mutations
Python | Rust |
---|---|
|
|
The &mut
on the Rust side means that we’re taking a mutable reference. Essentially, this means that add_one
is allowed to read and change the list.
You may hear the term “ownership” when talking about references. In this example, main
“owns” the list, and add_one
is “borrowing” it. Since add_one
is just “borrowing” it, add_one
has to give the list back to main
once it finishes running (this happens automatically).
Swap
Python | Rust |
---|---|
|
|
It’s actually impossible to make a swap
function in Python. Note that both a
and b
need to be mutable in order to create mutable references to them.
Evens
Python | Rust |
---|---|
|
|
Different ways to get the even elements of a list. I used i32
instead of usize
here just for fun; any integer type would work.
The &
means immutable borrow, which means that simple
can read the list, but not modify it.
Square Root
Python | Rust |
---|---|
|
|
Instead of null
, Rust has the Option<T>
type. An Option<usize>
is either a Some(usize)
or a None
. If you are handed an option, you can figure out the variant with a match
or if let
statement.