Rust for Pythonistas

Lesson 2 of 26

A tiny app: a function and a module

Now grow the hello project from lesson 1 the way you would grow a Python package. First you write a function, then you move it into its own module file, then you import it and run the program.

Don't worry about every symbol yet. &str, String and format! get their own lessons later. Here the goal is the shape of a small Rust program.

A function in the same file

The Python function has type hints. Rust needs them: every parameter and the return value have a type.

Python
def greet(name: str) -> str:
    return f"Hello, {name}!"


def main() -> None:
    print(greet("Ferris"))


if __name__ == "__main__":
    main()
Rust
fn greet(name: &str) -> String {
    format!("Hello, {name}!")
}



fn main() {
    println!("{}", greet("Ferris"));
}
Output
Hello, Ferris!

Move it into its own module

In Python, a new file greeting.py is a module you can import right away. In Rust you also create a file, src/greeting.rs, but you must declare it in main.rs with mod greeting;. Rust also hides everything by default: pub makes the function usable from other modules. Both programs print Hello, Ferris!.

Python files
# src/hello/greeting.py
def greet(name: str) -> str:
    return f"Hello, {name}!"


# src/hello/__init__.py
from hello.greeting import greet


def main() -> None:
    print(greet("Ferris"))
Rust files
// src/greeting.rs
pub fn greet(name: &str) -> String {
    format!("Hello, {name}!")
}


// src/main.rs
mod greeting;

use greeting::greet;

fn main() {
    println!("{}", greet("Ferris"));
}

Forgetting pub is a compile error

A module can also be written inline, with mod greeting { ... } in the same file. It works exactly like src/greeting.rs. Later lessons use this form a lot, because one file fits in the browser. Without pub, the function is private to its module. Python lets you call a _private function anyway. Rust refuses to compile.

Python
def _greet(name: str) -> str:
    return f"Hello, {name}!"





print(_greet("Ferris"))
Rust
mod greeting {
    fn greet(name: &str) -> String {
        format!("Hello, {name}!")
    }
}

fn main() {
    println!("{}", greeting::greet("Ferris"));
}
Output
Hello, Ferris!

Where the Python analogy breaks

Cheat card

PythonRust
def greet(name: str) -> str:pub fn greet(name: &str) -> String {
return f"Hello, {name}!"format!("Hello, {name}!") // last line, no ;
# new file src/hello/greeting.py// new file src/greeting.rs, plus "mod greeting;" in main.rs
from hello.greeting import greetuse greeting::greet;
greeting.greet("Ada")greeting::greet("Ada")
def _helper(): ... # private by conventionfn helper() { } // private unless pub
print(greet("Ada"))println!("{}", greet("Ada"));

← Your first Rust project Hello, variables and mut →