The Rust Programming Language
The Rust Programming Language

The Rust Programming Language — Collections — Structs

Ankit Tanna
3 min readOct 11, 2023

--

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:

  1. As you can see, you need to use struct keyword to define a struct.
  2. You need to give a name, in our case Point.
  3. You can define the properties inside the struct, i.e. x, y and z.
  4. 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: {}"…

--

--