How Rust Struct are Similar to Classes in OOP

How Rust Struct are Similar to Classes in OOP

Classes in Rust?

How Rust Struct are Similar to Classes in OOP

If you have been working in Rust language, and you come from an OOP background then you might have wondered how similar the concept of classes and rust struct is. The first language that I learned was rust language. Before learning rust I had a little bit of an idea of programming languages and the fundamentals. In high school, we learned the basic concepts of programming using C language. Before that, in my 10th grade, we learned programming using GWBASIC (Hey, it helped Ok).

However, I knew the concepts but still I was not very good. During my summer breaks, I took admission in the PIAIC IoT (Internet of Things) program. In the first quarter, we learned the rust language. I was really sure that I would grasp all the concepts really easily.

Well, the start was easy, I was flying through the fundamentals. Then came the part on which I pulled my hair. The ownership, strings, traits, etc. But, I managed to pull through. After rust language, I started learning Python. Let me tell you, that was the point when I found out the meaning of life. Just kidding, but Python helped me in deepening my knowledge so much more. I learned a lot. The way I looked at rust, changed. Everything finally made sense. At this time I realized that oop in rust exists.

OOP in Rust?

How Rust Struct are Similar to Classes in OOP

That is when I was first introduced to OOP (Object Oriented Programming). During this time, I found out how to make use of documentation, libraries, etc. It was a new step in my learning journey. That is when I realized how smart rust language developers are.

Well, I am not here to tell you about my journey. I am here to tell you how I came to the realization that how classes and structs are similar.

Introduction to Structs in Rust Language

How Rust Struct are Similar to Classes in OOP

There are no classes in rust but structs.

The definition of rust struct in The Book is:

A struct, or structure, is a custom data type that lets you name and package together multiple related values that make up a meaningful group.

Sounds really familiar right? C language also contains structures that are similar to the rust struct.

But if we dig deep down in rust struct, we will discover that structs are way different then C structures. C structures are a group of variables with different data types represented by a single name, and that is pretty much it. There is nothing much that you can do. You can define functions that can take this structure and process it, but it is very generic and does not provide context. This where rust struct differs.

In rust struct, you define data just like in C language. You use a keyword struct and then you give the name. Inside the curly braces, you enter the names and types of the pieces of data, which are known as fields.

struct User {
name: String,
age: u32,
}

Here we have defined a struct called User that stores the name and age of the user. To use the struct after you have defined it, you create an instance of that struct. Classes and structs have instances, so you can see the “oop in rust” when you look at the code.


let user1 = User {
name: String::from("John Doe"),
age: 32,
}

Here we have created the instance of User. The variable that holds the values now has a data type of User and values in the name and age field are “John Doe” and 32 respectively.

Until now, everything that we have done is similar to C. Here comes the OOP in Rust part. I said earlier that there are no contextualized functions in C structures. In rust struct though, we have functions known as methods which are defined the context of the structs. Here is how you define a method for a rust struct that we defined earlier.


impl User {
fn name(&self) -> String {
return self.name
}
}

To define a function in the context of the rust struct, you start an implementation block. Then you define the functions. The function name defined here is returning the name value of the User instance that was passed in. To call the method on our instance, we will do this:

user1.name()

The &self  in the function signature will take the instance of the rust struct, user1 is the instance in our example.

Classes and Structs

Alright, so the people coming from oop background will start to realize the similarities. Classes and structs are similar. After looking at the code examples above, we can get a vague idea of how the developers implement oop in rust. We can see how structs can act as classes in rust and how oop in rust can be achieved. Let us properly look at the similarities.

Similarities in classes and structs

How Rust Struct are Similar to Classes in OOP

Attributes

The first thing which clicks in mind after looking at rust struct’s fields is the class attributes in oop. When you define a class you provide some attributes in which the instance data will be stored later. The rust struct fields are so similar to the classes in oop. Both classes and structs need attributes to work upon. The value of the attributes can be modified and can be used in the program easily. You can think of the ways in which you can use rust struct as classes in rust. Unlike Java, if the structs are defined in the same module, you do not explicitly have to make the fields public.

After looking at the instance definition, you can understand why structs can act as classes in rust

Methods

Another similarity between classes and structs in rust is the methods. The contextualized functions. In OOP languages, methods are used extensively to work with the attributes of the object. The getter and setter methods are used to read and update values. Similarly, methods in rust struct can be defined in any way. You can see, how structs in rust language can act as classes in rusts.

They can be used in exactly the same way as OOP. Methods in rust can be used to update values, read values. It depends on the programmers in what way they are going to implement the methods.

The function definition is also very similar. Methods defined rust structs always take &self as the first argument. If you have a background in Python or Java, you can easily identify this similarity.

You can call structs as classes of rust.

Interface

Trait is a feature by which we can tell the Rust language compiler about the functionality a particular type has and can share it with other types. In Java, an interface does the same thing. If we can call similar methods on different types we can say that the types have the same behavior. We achieve this functionality in rust via traits.

In rust language, traits are used to define shared behavior and to create inheritance. It depends on the developer on how they want to use it.

We will see an example in which we will define a trait and will see how a function can be made to accept two different types as parameters.

First, we will define two structs.


struct Student {
name: String,
class: String,
}


struct Teacher {
name: String,
subject: String
}

Here we have defined two structs that are of two different data types. Now we will define a trait called Information. In that trait, we will have a method called show. When the trait is implemented on Student, the show method will return the class field’s value, and when the trait is implemented on the Teacher, the method will return the subject the teacher teaches.


pub trait Information {
fn show(&self) -> String;
}


impl Information for Student {
fn show(&self) -> String {
return self.class
}
}


impl Information for Teacher {
fn show(&self) -> String {
return self.subject
}
}

We just created an interface!. It is very similar to the concept of the interface in other OOP languages. You can get the hang of OOP in rust if you come from an oop background. After you get the hang of structs and traits in rust, you will be able to see the similarities in classes and structs.

Why not just add classes in Rust?

How Rust Struct are Similar to Classes in OOP

After reading all of this. You might be thinking that why the developers did not just add class keywords like C++ and Java. If they were keen on adding oop in rust, they could have made a better syntax which would be understandable when you look at it the first time. So why cannot just add classes in rust and make life easy for everyone?

The developers of rust language do not provide any clear answers related to this question. The answers that do exist are really different from one another. Everyone has a different opinion.

Before proceeding further, you should know that I am still a student. So the opinions that I will share should be taken as a grain of salt.

Rust language is hugely inspired by the C language. Rust is capable of doing low-level systems programming. I think after the developers added structs in the rust language the idea of oop in rust came to their mind. As they could not just remove everything and implemented classes in rust.

So they added oop without changing the struct concept. In this way, they were able to merge classes and structs in an oop fashioned way. You can say that it was just a design choice. Someone who is interested in low-level systems programming in rust, they can easily grasp the concept due to C language. For the people coming from the OOP background, they can also merge their previous knowledge in understanding concepts of oop in rust.

Conclusion

Rust is a general-purpose programming language. It was designed in a way such that people from any programming background can use it comfortably. Adding classes in rust or oop in rust could have been a reason to call rust language as Object Oriented. You should know that other than oop in rust there are some features that relate to functional programming too.

Adding specific features could have titled rust as a language for a specific paradigm. This is why in rust the similarities between classes and rusts would have to be created using a different way. In a more general-purpose way.

After reading this article, I hope you understand how classes and structs are similar. Although I did not dig deeper or this article would have been very long. You can look at this article to know more about oop in rust.

If you want to read more take a look at these articles.

Leave a Reply

Your email address will not be published. Required fields are marked *