Chapter 4 of 8

Object-Oriented Programming in Rust

Object-Oriented Programming in Rust

Introduction to OOP Concepts

Rust supports object-oriented programming (OOP) concepts through the use of structs, enums, and traits. In this chapter, we will explore how to apply OOP principles in Rust.

Key Concepts

  • Encapsulation: Bundling data and methods that operate on that data within a single unit, such as a struct.

  • Abstraction: Hiding implementation details and exposing only necessary information through public methods.

  • Inheritance: Implementing traits to inherit behavior from other types.

Practical Examples

// Define a struct to represent a rectangle
struct Rectangle {
    width: u32,
    height: u32,
}

// Implement methods for the Rectangle struct
impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

// Define a trait for shapes
trait Shape {
    fn area(&self) -> u32;
}

// Implement the Shape trait for Rectangle
impl Shape for Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle { width: 10, height: 20 };
    println!("Area: {}", rect.area());
}

In this example, we define a Rectangle struct and implement methods for it. We also define a Shape trait and implement it for Rectangle, demonstrating inheritance of behavior. This code showcases encapsulation, abstraction, and inheritance in Rust. By applying OOP concepts, we can write more organized, maintainable, and reusable code.

PreviousData Structures and Collections