Structs in Rust are kind of a mixture of an interface
and a class
from TypeScript/JavaScript. Structs, like tuple, cannot be altered. We cannot change the properties of the object during the lifecycle of the program.
Structs can be defined using struct
keyword in Rust. Unlike tuples, which are index based, we have properties of an object in a struct and hence they are based on the name of the properties in an object. Have a look at the below code snippet:
struct Point {
x: i64,
y: i64,
z: i64
}
Observations:
- As you can see, you need to use
struct
keyword to define a struct. - You need to give a name, in our case
Point
. - You can define the properties inside the struct, i.e.
x
,y
andz
. - You can mention the types of each and every property, i.e.
i64
.
When declaring a struct, you need to mention the name of the struct you are declaring. See the below code snippet:
struct Point {
x: i64,
y: i64,
z: i64
}
fn main() {
let point: Point = Point { x: 0, y: 1, z: 2 };
let point1: Point = new_point(3, 4, 5);
let point2: Point = new_point2(6, 7, 8);
println!("Point x: {}", point.x);
println!("Point y: {}"…