Structs, Traits, and Enums
Learn the basic way to organize data.
Structs
A struct is a data structure that allows us to group related features.
It can be compared to a class in an OOP language. We can have:
- Public and private methods through
impl. - Public and private properties through
fields. - Multiple inheritance through traits.
Spot and solve an error in the above code.
We can use the impl keyword to define implementations on types, sometimes the struct needs some methods to increase functionalities, in that case we can implement them inside an impl.
As we can see from the above code, we can create class methods and instance methods.
In the method total_inventory, we can define instance methods using &self as a parameter.
Traits
In other languages, we have different ways to share functionality like Inheritance, Mixins, or Interfaces. In Rust we have traits.
They are used to share functionality between structs.
For example, if we are building an application that performs the same calculations over different types, we can create a trait to encapsulate the functionality and calls it through the impl keyword over the struct definition.
We can also use traits as parameters to restrict what is allowed in the arguments.
In the below code, we use a more concise way to pass a trait as an argument. We use the impl keyword for that purpose.
We can use more than one trait bounds.
We can also return a struct that implements specific traits.
Enums
An enum is a data structure that allows different variants that are related.
Next, let’s test our understanding of this lesson.
Quiz
How should we approach the task of migrating a math application to Rust? 1
What is the correct way to create a model for square shapes?
trait Square {
length: f64,
unit: UnitMeasurement
}
struct Square {
length: f64,
unit: UnitMeasurement
}
struct Square {
length: i32,
unit: UnitMeasurement
}