Python to Rust

Free Python to Rust Code Converter

No email required. 100% free. Done in 30 seconds.

Transform your code from Python to Rust with our free AI-based code convertion tool. If you like what you see, we also create documentation for your code! We don't ever store your code or any representation of it in our databases, but it will be shared with the LLM of our choice for processing.

Other tools






Ionic + Angular










React Native


Ruby on Rails






How to convert from Python to Rust

Converting from Python to Rust can initially seem daunting due to the differences in syntax, paradigms, and features between the two languages. However, by understanding the core concepts in Rust and how they map to what you know in Python, you can make the transition smoother. This comprehensive guide will show you how to convert Python code to Rust, covering essential aspects and providing easy-to-understand examples.

Why Convert Python to Rust?

Before diving into the conversion process, it's crucial to understand why you might want to convert Python code to Rust:

  • Performance: Rust is a systems programming language designed for performance and safety. It can significantly outperform Python in execution speed.
  • Memory Safety: Rust ensures memory safety by using a strict ownership model without a garbage collector, minimizing potential runtime errors.
  • Concurrency: Rust's concurrency model makes it easier to write safe and concurrent code, unlike Python's Global Interpreter Lock (GIL).

Basic Differences Between Python and Rust

Understanding fundamental differences between Python and Rust is the first step in the conversion process:

  • Typing: Python is dynamically typed, while Rust is statically typed.
  • Memory Management: Python uses garbage collection; Rust uses ownership and borrowing.
  • Syntax: Python code is generally more concise due to its high-level nature. Rust requires more boilerplate but provides more control.

Setting Up Your Rust Environment

Before you start converting Python code to Rust, set up your Rust environment:

  1. Install Rust: Follow the instructions on the official Rust website to install Rust on your system.
  2. Cargo: Rust's package manager (Cargo) is essential for managing your Rust projects.
  3. IDE Support: Use an IDE like Visual Studio Code or IntelliJ IDEA with Rust plugins for a better development experience.

Converting Python Data Types to Rust

One of the first hurdles is converting data types from Python to Rust.

Simple Data Types

Python Type Rust Type
int i32 or i64
float f32 or f64
str String
bool bool


Python Type Rust Type
list Vec<T>
tuple (T1, T2, ...)
dict HashMap<K, V>
set HashSet<T>

Converting Functions and Methods

Python Example

def add(a, b):
    return a + b

Rust Equivalent

fn add(a: i32, b: i32) -> i32 {
    a + b

Error Handling

Python uses exceptions for error handling, whereas Rust employs the Result and Option types.

Python Example

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

Rust Equivalent

fn divide(a: f64, b: f64) -> Result<f64, String> {
    if b == 0.0 {
        return Err(String::from("Cannot divide by zero"));
    Ok(a / b)

Converting Loops and Control Flow

For Loop

Python Example
for i in range(5):
Rust Equivalent
for i in 0..5 {
    println!("{}", i);

While Loop

Python Example
i = 0
while i < 5:
    i += 1
Rust Equivalent
let mut i = 0;
while i < 5 {
    println!("{}", i);
    i += 1;

Ownership and Borrowing

Rust's ownership model is the most significant difference from Python. In Rust, each value has a single owner, and the value is dropped (freed) when the owner goes out of scope.


fn main() {
    let s1 = String::from("hello");
    let s2 = s1; // Ownership moves from s1 to s2
    // println!("{}", s1); // This would cause a compile-time error

Structs and Classes

Rust doesn't have classes like Python but uses structs to achieve similar functionality.

Python Class

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

Rust Struct

struct Point {
    x: i32,
    y: i32,

impl Point {
    fn new(x: i32, y: i32) -> Point {
        Point { x, y }


Converting code from Python to Rust involves understanding Rust's syntax, ownership model, and type system. While initially challenging, this thorough guide provides you with the fundamental knowledge to start converting your Python code to Rust efficiently. Leveraging Rust’s performance advantages and memory safety features will empower you to write more reliable and performant software.

Document your code using AI

Sign up now
& free your developers' time

Start for free

Join thousands of companies documenting their code using AI.

Frequently Asked Questions

This free AI tool does its best to generate professional documentation. However, it's missing some context from other related files. The paid version takes into account different files to generate documentation for each use case, apart from the documentation of every file. You have also the possibility of add custom concepts to improve the knowledge of your codebase.

No. You don't have to enter any personal information to use Codex's free code documentation tool — it's 100% free.

No. An encrypted version of your code is stored only while its being processed and it's deleted immediately.

If you can work with a custom Azure model in your own account, let us know. If not, Codex also works with open source models that can run on-premises, on your own servers, so your data is always yours. Feel free to get in touch with us!