Skip to main content
โšก Calmops

Structs in Rust

Structs in Rust are custom data types that let you name and package together multiple related values. They are similar to “structs” in C/C++ or “objects” in other languages, but without methods by default. Structs are fundamental for building complex data models in Rust.

Defining a Struct

You define a struct using the struct keyword, followed by the struct name and its fields.

struct User {
    username: String,
    email: String,
    sign_in_count: u64,
    active: bool,
}

Creating an Instance

You create an instance of a struct by specifying values for each field.

fn main() {
    let user1 = User {
        username: String::from("alice"),
        email: String::from("[email protected]"),
        sign_in_count: 1,
        active: true,
    };
}

Accessing and Modifying Fields

You can access fields using dot notation. If the instance is mutable, you can also modify its fields.

fn main() {
    let mut user1 = User {
        username: String::from("bob"),
        email: String::from("[email protected]"),
        sign_in_count: 1,
        active: true,
    };

    user1.email = String::from("[email protected]");
}

Struct Update Syntax

You can create a new struct instance using most of the values from another instance.

fn main() {
    let user1 = User {
        username: String::from("carol"),
        email: String::from("[email protected]"),
        sign_in_count: 1,
        active: true,
    };

    let user2 = User {
        email: String::from("[email protected]"),
        ..user1
    };
}

Tuple Structs

Tuple structs are similar to regular structs, but their fields have no namesโ€”just types.

struct Color(i32, i32, i32);

fn main() {
    let black = Color(0, 0, 0);
}

Unit-Like Structs

Unit-like structs have no fields. They can be useful for implementing traits.

struct AlwaysEqual;

fn main() {
    let subject = AlwaysEqual;
}

Methods on Structs

You can define methods for structs using impl.

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

fn main() {
    let rect = Rectangle { width: 30, height: 50 };
    println!("The area of the rectangle is {}.", rect.area());
}

Summary

  • Structs group related data together.
  • Fields can be accessed and modified using dot notation.
  • Methods can be implemented for structs using impl.
  • Rust also supports tuple structs and unit-like structs for special use cases.

Structs are a core building block for modeling data in Rust programs.

Comments