Rust vs Python book presents common code blocks written both in idiomatic Rust and Python.

The book is indexed at rust-indexed.com

Read line from stdin

Rust

#![allow(unused)]
fn main() {
println!("Type something")
let mut line = String::new();
std::io::stdin.read_line(&mut line)
}

Python

line = input("Type something")

Print formatted string

Rust

#![allow(unused)]
fn main() {
let x = 5
println!("Variable x equals to {}", x)
}

Python

x = 5
print(f"Variable x equals to {x}")

Random number in range

Rust

#![allow(unused)]
fn main() {
use rand::Rnd;
let n = rand::thread_rng().gen_range(0..10)
}

Python

import random
n = random.randint(0, 10)

String to int

Rust

#![allow(unused)]
fn main() {
let my_str = "1024".to_string();
let my_int = my_string.parse::<u32>();
}

Python

x = "1024"
i = int(x)

Exit with code

Rust

#![allow(unused)]
fn main() {
std::process::exit(255)
}

Python

import sys
sys.exit(255)

Read command line arguments

Rust

#![allow(unused)]
fn main() {
let args = std::env::args(); // iterator
}

Python

import sys
args = sys.argv # list

Enumerate string

Rust

#![allow(unused)]
fn main() {
for (i, ch) in s.chars().enumerate() {
}
}

Python

for i, ch in enumerate(s):
    ...

Enumerate vector

Rust

#![allow(unused)]
fn main() {
for (i, element) in vector.iter().enumerate() {
}
}

Python

for i, element in enumerate(vector):
    ...

Print line separator

Rust

#![allow(unused)]
fn main() {
println!("{}", "-".repeat(80))
}

Python

print("-" * 80)

Map vector

Rust

#![allow(unused)]
fn main() {
let v = vec![1, 2, 3];
let new_vec = v.iter().map(|num| {
    num * 2
});
}

Python

v = [1, 2, 3];
new_vec = map(num * 2, v)

Ternary operator

Rust

#![allow(unused)]
fn main() {
let a = 5;
let x = if a > 10 { 20 } else { 30 };
}

Python

a = 5
x = 12 if a > 10 else 30;

Get min and max of two values

Rust

#![allow(unused)]
fn main() {
use std::cmp::{min, max};
let (max_v, min_v) = (max(10, 50), min(10, 50));
}

Python

max_v, min_v = max(10, 50), min(10, 50)

Read/write from/to file

Rust

#![allow(unused)]
fn main() {
use std::fs::File;
use std::io::{Read, Write};

let mut f = File::create("foo.txt").unwrap();
write!(f, "Hello, world!").unwrap();

let mut f = File::open("foo.txt").unwrap();
let mut content = String::new();
f.read_to_string(&mut content).unwrap();
}

Python

with open("foo.txt", "w") as f:
    f.write("Hello, world!")

content = open("foo.txt").read()

Get current timestamp in seconds

Rust

#![allow(unused)]
fn main() {
use std::time::{SystemTime, UNIX_EPOCH};
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs()
}

Python

import time
now = int(time.time())

Async sleep

Rust

#![allow(unused)]
fn main() {
use std::time::Duration;
use tokio::time;
time::sleep(Duration::from_secs(2)).await;
}

Python

import async
await asyncio.sleep(2)

Increment dict value

Rust

#![allow(unused)]
fn main() {
let mut map: HashMap<u64, u64> = HashMap::new();
*map.entry(50).or_insert(0) += 1;
}

Python

map = {}
map[50] = map.get(50, 0) + 1

Push value to dict of vectors

Rust

#![allow(unused)]
fn main() {
let mut map: HashMap<u64, Vec<u64>> = HashMap::new();
map.entry(50).or_default().push(10);
}

Python

map = {}
map.setdefault(50, []).append(10);

Measure execution time

Rust

#![allow(unused)]
fn main() {
use std::time::Instant;

let start = Instant::now();
// ...
let duration = start.elapsed();
}

Python

import time

start = time.time()
# ...
duration = time.time() - start

Read environment variable

Rust

#![allow(unused)]
fn main() {
if let Ok(value) = std::env::var("MY_ENV_VAR") {
    println!("MY_ENV_VAR={value}")
}
}

Python

import os

if os.environ.get("MY_ENV_VAR"):
    value = os.environ["MY_ENV_VAR"]
    print(f"MY_ENV_VAR={value}")

Implement custom formatting for a data type

Rust

#![allow(unused)]
fn main() {
use std::fmt::Display;

struct Animal(String);

impl Display for Animal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "My name is {}", self.0)
    }
}
}

Python

class Animal:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f"My name is {self.name}"

Zip two vectors

Rust

#![allow(unused)]
fn main() {
for (a, b) in vec1.iter().zip(vec2) {
    println!("{a} {b}");
}
}

Python

for a, b in zip(vec1, vec2):
    print(f"{a} {b}")

Read a file line by line

Rust

#![allow(unused)]
fn main() {
let f = File::open("foo.txt").unwrap();
for line in BufReader::new(&f).lines().filter_map(Result::ok) {
    // The line doesn't contain trailing CR/LF
}
}

Python

for line in open("foo.txt"):
    # The line contains trailing CR/LF