A struct or structure is a custom Data Type that is a collection of related values that are put together to form a meaningful group. They are simillar to Object attributes as in Object Oriented Languages. Structs in Rust are simillar to how we define them in C and C++ but structs in Rust can do more than structs in C and C++.
Structs
To define a struct in Rust we use the struct keyword followed by the name of the struct and then {}
and inside these we put the values that are related to the struct.
struct SuperHero {
name: String,
hero_name: String,
age: u32,
active: bool,
}
To use the struct we define a variable to which we will assign the struct with the name and age value inside the {}
which we can later use in other places.
let bruce = SuperHero {
name: String::from("Bruce"),
hero_name: String::from("Batman"),
age: 30,
active: true,
};
We can use the dot notation to reference a property of the struct and can also use the dot notation to update the property of the Person.
bruce.name // Bruce
bruce.name = String::from("Bruce Wayne");
bruce.name // Bruce Wayne
But to allow the values of a struct to be updates later, the instance must be mutable.
let mut bruce = SuperHero {
// ...
};
Creating Instaces With Values From Other Instances
We can also create instances from other inctances with sharing the values of other instances as well. For example:
let mut clark = SuperHero {
name: String::from("Clark Kent"),
hero_name: String::from("SuperMan"),
..bruce
};
Now clark will inherit the same values as the bruce except the ones we defined ourselves like name
and hero_name
. This show that clark
is the same age as bruce
and is also active.
Struct Methods
As said before that Rust structs are much more than the C and C++ becuase we can implement methods on the struct that we can call on the strcut to modify some value inside the instance of the struct. We implement a method by using impl
keyword and after that the name of the struct on which we want to implement it and then inside the {}
we define a new function with &self
as the first argument which represents the instance itself just like the keyword self
in Python and this
in JavaScript.
impl Hero {
fn say_my_name(&self) {
println!("{}", slef.name)
}
}
bruce.say_my_name() // Bruce Wayne
Tuple Struct
Rust also have Tuple Struct which we define the same way but without any name and {}
.
struct RGB(i32, i32, i32);
let black = RGB(0, 0, 0);
We can reference a value of the tuple struct by using its index number with dor notation.
black.0 // 0
black.1 // 0
black.2 // 0
And that all for Struct. This one was a little simple for me to understand as I have worked with struct before in C while learning about Linked Lists and Hash Tables but still Rust struct are more powerful than they are in C and maybe some other languages.