Chapter 20: Object-Oriented Programming in Rust

Object-Oriented Programming (OOP) is a paradigm central to languages like C++ and Java, often characterized by features such as classes, inheritance, and virtual methods. For C programmers, C++ introduces these concepts on top of C’s procedural foundation. OOP aims to structure software around objects that bundle data and behavior (encapsulation), allow types to inherit properties from others (inheritance), and enable interaction with different types through a common interface (polymorphism).

Rust supports the core goals of OOP, including encapsulation and polymorphism, but it achieves them differently. Rust deliberately omits class-based implementation inheritance, a cornerstone of traditional OOP. Instead, it leverages a combination of features: data structures (structs and enums) with associated methods (impl blocks), traits for defining shared behavior (interfaces), generics for compile-time polymorphism, its module system for encapsulation, and a preference for composition over inheritance. This chapter explores how Rust provides OOP-like capabilities using its distinct approach.