Sling Academy
Home/Rust/Defining Basic Structs in Rust and Their Named Fields

Defining Basic Structs in Rust and Their Named Fields

Last updated: January 03, 2025

Introduction to Structs in Rust

Structures, or structs in Rust, are used to create custom data types that let you name and package together multiple different data types. They are similar to structures in other programming languages like C or classes in object-oriented languages. Structs are a key feature of Rust, making your code cleaner and more readable by collecting related data into one meaningful group.

Basic Definition of a Struct

In Rust, a struct is defined using the struct keyword followed by the name of the struct and its fields enclosed in curly braces. Fields inside structs can have different types, and each must have a name. Here is a basic example:

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

This struct defines a User with fields for a username, email, the number of times they've signed in, and whether they are currently active.

Instantiating a Struct

Once you've defined a struct, you'll want to create instances of it. You do this by specifying the struct name followed by a curly brace containing field names and their values:

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

Here, an instance named user1 is created with its fields initialized with specific values.

Accessing Struct Fields

Fields of a struct can be accessed using the dot (.) notation. This allows you to use individual pieces of the data stored in a struct. For example:

println!("Username: {}", user1.username);
println!("Email: {}", user1.email);

The above commands print the username and email of the user1.

Updating a Struct

Rust provides a convenient way to create a new instance of a struct that uses some of the values from an old instance but overwrites other values. Here is how you achieve this:

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

This technique, known as struct update syntax, allows the creation of user2 with the same username, signin count, and active status as user1, but with a different email address.

Tuple Structs

Rust also provides tuple structs which are a way of creating a struct without naming the fields. These are useful for giving the whole struct a name but not naming each field. Here’s how to define and use a tuple struct:

struct Point(i32, i32, i32);

let origin = Point(0, 0, 0);

Tuple structs can be accessed by using dot notation with an index, like a tuple:

let x = origin.0;

This example creates a Point instance representing the origin of a three-dimensional space and accesses its x-coordinate.

Conclusion

Structs are a fundamental feature in Rust for bundling related data together. Learning how to define and manipulate them effectively is essential for mastering the language. Experiment with different builds and structure types to better understand their capabilities and constraints.

Next Article: Working with Tuple Structs and Unit-Like Structs in Rust

Previous Article: Introduction to Rust Structs: A Foundational Overview

Series: Working with structs in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior