Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Welcome to Rust vs Python

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

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

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

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}")

Read command line arguments

Rust

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

Python

import sys
args = sys.argv # list

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}")

Print line separator

Rust

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

Python

print("-" * 80)

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)

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

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)

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

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}")

Memoization

Rust

#![allow(unused)]
fn main() {
;cargo add cached

use cached::proc_macro::cached;

#[cached]
fn fib(n: u64) -> u64 {
    ...
}
}

Python

from functools import cache

@cache
def fib(n):
    ...

Deque

Rust

#![allow(unused)]
fn main() {
use std::collections::VecDeque;

let mut d = VecDeque::from([2,3]);
d.push_back(4);
d.push_front(1);
d.pop_back();
d.pop_front();
}

Python

from collections import deque

d = deque([2,3])
d.append(4)
d.appendleft(1)
d.pop()
d.popleft()

Remove file

Rust

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

fs::remove_file("file.txt")?;
}

Python

import os

os.remove("file.txt")

Join path

Rust

#![allow(unused)]
fn main() {
use std::path::PathBuf;

let path = PathBuf::from("home")
    .join("user")
    .join("file.txt");
}

Python

import os

path = os.path.join("home", "user", "file.txt")

Find the longest string

Rust

#![allow(unused)]
fn main() {
let words = vec!["cat", "elephant", "dog"];

let longest = words.iter().max_by_key(|w| w.len());
}

Python

words = ["cat", "elephant", "dog"]

longest = max(words, key=lambda w: len(w))