Python vs. Rust
Many features of the Rust language will be familiar to Python programmers. Many examples are listed below. For more code comparisons, see py2rs.
Concept
Python
Rust
tuples
my_tuple = (1, 2, 3)
# Access the element at index 1
n = my_tuple[1]
let my_tuple = (1, 2, 3);
// Access the element at index 1
let n = my_tuple.1;
destructuring
(x, y, z) = my_tuple
let (x, y, z) = my_tuple;
"don't care" / wildcard
(a, _, b) = my_tuple
let (a, _, b) = my_tuple;
lambdas / closures
# Lambdas are anonymous functions
f = lambda x: x * x
f(4)
// Closures are anonymous functions
let f = | x | x * x;
f(4)
type annotations
x: int = 42
let x: i32 = 42;
ranges
range(0, 10)
0..10
match-case / match blocks
match x:
case 1:
...
case _:
...
match x {
1 => { ... },
_ => { ... }
}
for-in loops
for i in range(0, 10):
...
for i in 0..10 {
...
}
If-else conditionals
if x > 10:
...
else:
...
if x > 10 {
...
} else {
...
}
While loops
while x < 10:
...
while x < 10 {
...
}
Importing modules
import math
use std::f64::consts::PI;
String formatting
"Hello, {}".format(name)
format!("Hello, {}", name)
List/Vector creation
lst = [1, 2, 3]
let lst = vec![1, 2, 3];