Python classes vs Rust structures

Antonov Mike - Dec 11 '23 - - Dev Community

I guess I should supplement my previous post. I have received valid criticism in private messages. Thank you for that. Now I'm going to try to talk about classes and structures.

These are two ways of defining custom data types in their respective languages, but they have some notable differences in their syntax, features, and usage.

Some of the similarities are:

1) Both Python classes and Rust structures can have fields that store data and methods that define behavior.
2) Both Python classes and Rust structures can implement inheritance, polymorphism, and encapsulation, which are the core principles of object-oriented programming.
3) Both Python classes and Rust structures can use constructors to initialize their instances with default or custom values.

Some of the differences are:

1) Python classes are dynamic and flexible, while Rust structures are static and strict. Python classes can add or remove fields and methods at runtime, and use decorators and metaclasses to modify their behavior. Rust structures have fixed fields and methods, and use traits and macros to extend their functionality.
2) Python classes use the self keyword to refer to the current instance within a method, while Rust structures use the self, &self, or &mut self parameters to indicate the ownership and mutability of the instance.
3) Python classes support multiple inheritance, which means a class can inherit from more than one class at the same time. Rust structures do not support multiple inheritance, but a structure can implement multiple traits and a trait can require multiple traits as bounds.

Python has a built-in garbage collector that manages the memory, while Rust uses the ownership and borrowing system to ensure memory safety and prevent memory leaks.

An example of how we can implement Player in Python and Rust

class Player:
    def __init__(self, name, color):
        self.name = name
        self.color = color
        pass

    def valid_player(self, piece_color):
        if self.color == piece_color:
            return True
        else:
            return False
Enter fullscreen mode Exit fullscreen mode
pub struct Player {
   name: String,
   color: String,
}

impl Player {
   pub fn new(name: String, color: String) -> Player {
       Player { name, color }
   }

   pub fn valid_player(&self, piece_color: &str) -> bool {
       self.color == piece_color
   }
}
Enter fullscreen mode Exit fullscreen mode

Image created by Bing and edited by me

Other articles about the similarities and differences between Rust and Python

  1. Python Classes vs. Rust Traits
  2. Python classes vs Rust structures
  3. Polymorphism in Rust and Python
  4. Abstraction in Rust and Python
  5. Encapsulation in Rust and Python
  6. Composition in Rust and Python
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .