Rust for Pythonistas

Error index

error[E0308]: mismatched types

In Python: A TypeError at run time, if that line ever runs.

A value has a different type than the code says. Rust never converts types for you.

Does not compile
fn main() {
    let age: i32 = "36";
    println!("{age}");
}
Fixed
fn main() {
    let age: i32 = "36".parse().unwrap();
    println!("{age}");
}

error[E0425]: cannot find value `totl` in this scope

In Python: NameError: name 'totl' is not defined, at run time.

A name that doesn't exist here: often a typo, or a variable from another block that already ended.

Does not compile
fn main() {
    let total = 10;
    println!("{}", totl);
}
Fixed
fn main() {
    let total = 10;
    println!("{}", total);
}

error[E0599]: no method named `upper` found for struct `String` in the current scope

In Python: AttributeError: 'str' object has no attribute ...

The type has no method with that name. Python names often differ in Rust: upper is to_uppercase. Sometimes the method exists but needs a use for its trait.

Does not compile
fn main() {
    let name = String::from("ada");
    println!("{}", name.upper());
}
Fixed
fn main() {
    let name = String::from("ada");
    println!("{}", name.to_uppercase());
}

error[E0384]: cannot assign twice to immutable variable `count`

In Python: No equivalent: Python lets you reassign any name.

Variables can't change unless they are declared with let mut.

Does not compile
fn main() {
    let count = 0;
    count += 1;
    println!("{count}");
}
Fixed
fn main() {
    let mut count = 0;
    count += 1;
    println!("{count}");
}

error[E0596]: cannot borrow `names` as mutable, as it is not declared as mutable

In Python: No equivalent: any Python list can be changed.

A method that changes the value (like push) needs the variable to be let mut, or a &mut borrow.

Does not compile
fn main() {
    let names = Vec::new();
    names.push("ada");
    println!("{:?}", names);
}
Fixed
fn main() {
    let mut names = Vec::new();
    names.push("ada");
    println!("{:?}", names);
}

error[E0382]: borrow of moved value: `a`

In Python: No error: b = a gives the same list a second name.

The value moved to a new owner, and the old name can't be used any more. Borrow with & or copy with .clone(). Look at the line where it moved, not only where it is used.

Does not compile
fn main() {
    let a = vec![1, 2, 3];
    let b = a;
    println!("{:?} {:?}", a, b);
}
Fixed
fn main() {
    let a = vec![1, 2, 3];
    let b = a.clone();
    println!("{:?} {:?}", a, b);
}

error[E0502]: cannot borrow `nums` as mutable because it is also borrowed as immutable

In Python: Changing a list while looping over it gives surprising results; for a dict it is RuntimeError: dictionary changed size during iteration.

Something is reading the value (here the loop) while something else wants to change it. Many readers or one writer, never both.

Does not compile
fn main() {
    let mut nums = vec![1, 2, 3];
    for n in &nums {
        if *n == 2 {
            nums.push(4);
        }
    }
    println!("{:?}", nums);
}
Fixed
fn main() {
    let mut nums = vec![1, 2, 3];
    for n in nums.clone() {
        if n == 2 {
            nums.push(4);
        }
    }
    println!("{:?}", nums);
}

error[E0499]: cannot borrow `s` as mutable more than once at a time

In Python: No equivalent: any number of names can change the same object.

Two &mut borrows of the same value are alive at once. Finish using the first before you make the second.

Does not compile
fn main() {
    let mut s = String::from("a");
    let r1 = &mut s;
    let r2 = &mut s;
    r1.push('b');
    r2.push('c');
    println!("{s}");
}
Fixed
fn main() {
    let mut s = String::from("a");
    let r1 = &mut s;
    r1.push('b');
    let r2 = &mut s;
    r2.push('c');
    println!("{s}");
}

error[E0507]: cannot move out of index of `Vec<String>`

In Python: No error: first = names[0] is one more reference to the same string.

Taking a String out of a Vec by index would leave a hole. Borrow it with &names[0], or copy it with .clone().

Does not compile
fn main() {
    let names = vec![String::from("ada"), String::from("bob")];
    let first = names[0];
    println!("{first}");
}
Fixed
fn main() {
    let names = vec![String::from("ada"), String::from("bob")];
    let first = &names[0];
    println!("{first}");
}

error[E0004]: non-exhaustive patterns: `Light::Yellow` not covered

In Python: No error: a match with no matching case silently does nothing.

A match must handle every variant. Add the missing arm, or a _ => arm for "everything else".

Does not compile
enum Light {
    Red,
    Yellow,
    Green,
}

fn main() {
    let light = Light::Green;
    let action = match light {
        Light::Red => "stop",
        Light::Green => "go",
    };
    println!("{action}");
}
Fixed
enum Light {
    Red,
    Yellow,
    Green,
}

fn main() {
    let light = Light::Green;
    let action = match light {
        Light::Red => "stop",
        Light::Yellow => "wait",
        Light::Green => "go",
    };
    println!("{action}");
}

error[E0277]: `Point` doesn't implement `std::fmt::Display`

In Python: No error: print(p) falls back to something like <Point object at 0x...>.

A trait the code needs is missing. Here {} needs Display. For debugging, derive Debug and print with {:?}. The same error code covers any missing trait, such as Send for threads.

Does not compile
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 1, y: 2 };
    println!("{}", p);
}
Fixed
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 1, y: 2 };
    println!("{:?}", p);
}

error[E0369]: binary operation `==` cannot be applied to type `Point`

In Python: No error, but a surprise: without __eq__, == compares identity, so two equal-looking objects are not equal.

The type doesn't support that operator. Add #[derive(PartialEq)] for ==, or implement the operator trait.

Does not compile
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = Point { x: 1, y: 2 };
    println!("{}", a == b);
}
Fixed
#[derive(PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = Point { x: 1, y: 2 };
    println!("{}", a == b);
}

error[E0609]: no field `email` on type `User`

In Python: AttributeError: 'User' object has no attribute 'email', at run time.

The struct has no field with that name. Every field is declared up front in the struct.

Does not compile
struct User {
    name: String,
}

fn main() {
    let user = User { name: String::from("ada") };
    println!("{}", user.email);
}
Fixed
struct User {
    name: String,
}

fn main() {
    let user = User { name: String::from("ada") };
    println!("{}", user.name);
}

error[E0061]: this function takes 2 arguments but 1 argument was supplied

In Python: TypeError: add() missing 1 required positional argument: 'b'

A call passes the wrong number of arguments. Rust has no default values, so every parameter must be passed.

Does not compile
fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn main() {
    println!("{}", add(1));
}
Fixed
fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn main() {
    println!("{}", add(1, 2));
}

error[E0433]: cannot find type `HashMap` in this scope

In Python: NameError: name 'HashMap' is not defined: a missing import.

A type or module isn't in scope. Usually a use line is missing; the help: line often names it.

Does not compile
fn main() {
    let mut ages = HashMap::new();
    ages.insert("ada", 36);
    println!("{}", ages["ada"]);
}
Fixed
use std::collections::HashMap;

fn main() {
    let mut ages = HashMap::new();
    ages.insert("ada", 36);
    println!("{}", ages["ada"]);
}

error[E0603]: function `greet` is private

In Python: No error: a leading _ is only a convention.

The item is private to its module. Add pub where it is defined.

Does not compile
mod greeting {
    fn greet(name: &str) -> String {
        format!("Hello, {name}!")
    }
}

fn main() {
    println!("{}", greeting::greet("Ada"));
}
Fixed
mod greeting {
    pub fn greet(name: &str) -> String {
        format!("Hello, {name}!")
    }
}

fn main() {
    println!("{}", greeting::greet("Ada"));
}

error[E0283]: type annotations needed

In Python: No equivalent: a list comprehension's brackets say what to build.

The compiler can't work out a type, most often what collect() or parse() should produce. Write it: let nums: Vec<i32> = .... Error E0282 says the same thing in other places.

Does not compile
fn main() {
    let nums = "1 2 3".split(' ').map(|s| s.parse::<i32>().unwrap()).collect();
    println!("{:?}", nums);
}
Fixed
fn main() {
    let nums: Vec<i32> = "1 2 3".split(' ').map(|s| s.parse::<i32>().unwrap()).collect();
    println!("{:?}", nums);
}

error[E0106]: missing lifetime specifier

In Python: No equivalent.

A function returns a reference, and the compiler can't tell which input it points into. Name it with a lifetime like 'a; the help: line shows where.

Does not compile
fn longest(a: &str, b: &str) -> &str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    println!("{}", longest("ab", "c"));
}
Fixed
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    println!("{}", longest("ab", "c"));
}

error[E0597]: `name` does not live long enough

In Python: No equivalent: Python keeps an object alive as long as anything refers to it.

A reference is still used after the value it points to was freed at its }. Keep the value alive longer, or store an owned copy instead of a reference.

Does not compile
fn main() {
    let r;
    {
        let name = String::from("ada");
        r = &name;
    }
    println!("{r}");
}
Fixed
fn main() {
    let name = String::from("ada");
    let r = &name;
    println!("{r}");
}

error[E0373]: closure may outlive the current function, but it borrows `name`, which is owned by the current function

In Python: No equivalent: Python threads can use any variable.

A thread (or a stored closure) might run after the function ends, so it can't borrow local variables. Add move so it owns them.

Does not compile
use std::thread;

fn main() {
    let name = String::from("ada");
    let h = thread::spawn(|| println!("{name}"));
    h.join().unwrap();
}
Fixed
use std::thread;

fn main() {
    let name = String::from("ada");
    let h = thread::spawn(move || println!("{name}"));
    h.join().unwrap();
}