OneBite.Dev - Coding blog in a bite size

Declare A Class In Rust

Code snippet for how to Declare A Class In Rust with sample and detail explanation

In Rust, a class is not a native concept as it is in object-oriented programming languages. However, with Rust, we can achieve similar functionality using struct and impl. In this article, we will go over how to declare a class-like construct in Rust.

Declaring A Class In Rust

First, let’s take a look at a simple example of defining a class-like construct in Rust.

struct Car {
    make: String,
    model: String,
    year: i32,
}

impl Car {
    fn new(make: &str, model: &str, year: i32) -> Car {
        Car {
            make: make.to_string(),
            model: model.to_string(),
            year: year,
        }
    }

    fn details(&self) {
        println!("The car is a {} {} from {}.", self.make, self.model, self.year);
    }
}

Code Explanation For Declaring A Class In Rust

Let’s break down what the above code is doing, step by step.

The keyword struct is used to define a structure named Car. This is similar to how we would declare a class in other languages. The members of the structure are variables make, model, and year. These are equivalent to instance variables.

Next, we have the keyword impl followed by the structure name. This allows us to define methods for the structure, which is similar to defining methods within a class.

The new function is akin to a constructor in other languages. We provide arguments to the function for make, model, and year. Inside its body, we return a new Car object with its variables assigned from the function arguments. The .to_string() method converts the input string references to actual String so that we can do copies when needed.

The details function is an instance method as it takes an immutable reference to self as a method argument. This is similar to the self keyword in Python or the this keyword in Java. Inside this function, we print out the details of the Car instance using the println! macro.

The &self in the function signifies that we are borrowing a reference to the struct. This allows us to use the values of our struct within our method without taking ownership.

This combination of struct and impl is how we can emulate a class in Rust. This approach allows us to maintain Rust’s principle of ownership and borrowing while still allowing us to logically group our data and its related functionality.

rust