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 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::prelude::*; let mut f = File::create("foo.txt").unwrap(); f.write_all(b"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 use chrono::offset::Utc; let now = Utc::now().timestamp() as u64 }
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, u64> = HashMap::new(); map.entry(50).or_default().push(0); }
Python
map = {}
map.setdefault(50, []).append(0);
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}")