w3resource

A Complete Guide to Rust Structs with Syntax and Examples


Understanding Structs in Rust: A Complete Guide

What is a Struct in Rust?

A struct (short for "structure") in Rust is a custom data type that lets you group related data together. Structs are essential for defining complex data types in Rust, allowing developers to encapsulate multiple fields into a single logical unit. They are similar to classes in object-oriented programming, but without methods by default.

Structs in Rust can be used to model real-world entities, making code more readable, maintainable, and type-safe.


Types of Structs in Rust

    1. Classic Structs: Define fields with names and types.

    2. Tuple Structs: Fields are identified by position.

    3. Unit-Like Structs: Structs with no fields, often used for marker types.


Syntax for Defining Structs

Classic Struct

Code:

struct Point {
    x: i32,
    y: i32,
}

Tuple Struct

Code:

struct Color(i32, i32, i32);

Unit-Like Struct

Code:

struct Marker;

Examples and Explanations

1. Defining and Using Classic Structs

Code:

// Define a struct
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    // Create an instance of the struct
    let rect = Rectangle {
        width: 30,
        height: 50,
    };

    // Access fields
    println!("Width: {}, Height: {}", rect.width, rect.height); // Width: 30, Height: 50
}

Explanation:

  • Rectangle is a classic struct with named fields width and height.
  • Fields are accessed using the dot notation.

2. Using Tuple Structs

Code:

// Define a tuple struct
struct Point(i32, i32, i32);

fn main() {
    // Create an instance
    let origin = Point(0, 0, 0);

    // Access fields by index
    println!("Point: ({}, {}, {})", origin.0, origin.1, origin.2); // Point: (0, 0, 0)
}

Explanation:

  • Tuple structs group values without naming fields.
  • Fields are accessed using their positional index.

3. Unit-Like Structs

Code:

// Define a unit-like struct
struct Marker;

fn main() {
    // Create an instance
    let _marker = Marker;

    println!("Unit-like struct created!");
}

Explanation:

  • Unit-like structs have no fields and are typically used for marker traits or flags.

4. Struct with Methods

Code:

// Define a struct with methods
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    // Method to calculate the area
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle {
        width: 30,
        height: 50,
    };

    // Call the method
    println!("Area: {}", rect.area()); // Area: 1500
}

Explanation:

  • impl block is used to define methods for the struct.
  • &self is a reference to the instance of the struct.

5. Destructuring Structs

Code:

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let point = Point { x: 10, y: 20 };

    // Destructure the struct
    let Point { x, y } = point;

    println!("x: {}, y: {}", x, y); // x: 10, y: 20
}

Explanation:

  • You can destructure a struct to extract its fields into variables.

6. Update Syntax

Code:

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p1 = Point { x: 10, y: 20 };

    // Create a new struct using an existing one
    let p2 = Point { x: 15, ..p1 };

    println!("p2: ({}, {})", p2.x, p2.y); // p2: (15, 20)
}

Explanation:

  • The .. syntax copies the remaining fields from another instance.


Key Advantages of Structs in Rust

    1. Encapsulation: Group related data together.

    2. Type Safety: Define custom types with clear boundaries.

    3. Reusability: Use structs as building blocks for larger programs.

    4. Flexibility: Choose between classic, tuple, or unit-like structs based on use case.

Rust Language Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust-tutorial/rust-structs-guide-syntax-examples.php