DEV Community

Cover image for Abstraction in Rust and Python. Simple examples

Abstraction in Rust and Python. Simple examples

Antonov Mike on February 27, 2024

Disclaimer The article contains code samples, but not theory and does not pretend to explain the theoretical basis of polymorphism in de...
Collapse
 
antonov_mike profile image
Antonov Mike
trait Printer {
    fn print_data(&self, data: &str);
}

struct DataPrinter;
Enter fullscreen mode Exit fullscreen mode

Declaring a method that does nothing, especially in the context of traits and structs in Rust, serves several purposes:

  1. Trait Definition: Defining a method in a trait that does nothing (i.e., has an empty body) is a way to specify a default behavior that can be overridden by any struct that implements the trait. This is useful for creating a base or interface that can be extended by other structs. The method in the trait acts as a placeholder for functionality that might be implemented differently by each struct that implements the trait.
  2. Default Behavior: By providing a default implementation of a method (even if it does nothing), you can ensure that any struct implementing the trait will have a method with that name. This is beneficial for code organization, as it groups related functionality under a single trait, making the code easier to understand and maintain.
  3. Flexibility and Extensibility: It allows for more flexible and extensible designs. Structs can choose to implement the method to provide specific functionality, or they can rely on the default (no-op) implementation. This flexibility is particularly useful in larger codebases where different parts of the code might need to interact with the same trait but require different implementations of its methods.
  4. Clarity and Documentation: Declaring a method that does nothing can also serve as documentation. It explicitly states that a method is part of the trait's contract, even if it doesn't do anything by default. This can be helpful for future developers working with the code, as it clearly indicates the expected interface of the trait and what methods are available for use.