LibraryDefining Structs

Defining Structs

Learn about Defining Structs as part of Rust Systems Programming

Defining Structs in Rust

In Rust, a

code
struct
(short for structure) is a custom data type that lets you package together multiple values of different types into a single, meaningful unit. Structs are fundamental for organizing data and creating complex data models in your programs. They are a core component of Rust's powerful systems programming capabilities.

What is a Struct?

Think of a struct like a blueprint for creating objects. You define the fields (variables) that make up the struct, and then you can create instances of that struct, filling in the values for each field. This allows you to represent real-world entities or abstract concepts in a structured way.

Structs group related data into a single unit.

Structs are like custom containers for data. You define the types of data each container will hold, and then you can create instances of these containers with specific values.

Structs are defined using the struct keyword, followed by the struct name and curly braces {}. Inside the braces, you list the fields, each with a name and a type. For example, a User struct might have fields for username (String), email (String), and sign_in_count (u64).

Defining a Basic Struct

Here's how you define a simple struct in Rust:

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

This Rust code defines a User struct. It has four fields: username and email, both of type String (for text), sign_in_count of type u64 (an unsigned 64-bit integer for counting), and active of type bool (for true/false values).

📚

Text-based content

Library pages focus on text content

Creating Instances of a Struct

Once you've defined a struct, you can create instances of it. When creating an instance, you must provide a value for each field. The order of fields when creating an instance doesn't have to match the definition order, but you must name each field.

Here's how to create an instance of the

code
User
struct:

rust
let user1 = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};

Accessing Struct Fields

You can access the values within a struct instance using dot notation.

rust
println!("Username: {}", user1.username);
println!("Email: {}", user1.email);
What keyword is used to define a custom data type that groups multiple values in Rust?

The struct keyword.

Struct Update Syntax

Rust provides a convenient syntax for creating a new instance of a struct that uses most of its values from another instance. This is called the struct update syntax.

rust
let user2 = User {
email: String::from("another@example.com"),
username: String::from("anotherusername"),
..user1 // Copies the remaining fields from user1
};

In this example,

code
user2
will have its
code
email
and
code
username
fields set to new values, while
code
active
and
code
sign_in_count
will be copied from
code
user1
. Note that if
code
user1.username
was not
code
Copy
, it would be moved, and
code
user1
would no longer be usable.

What is the syntax called that allows creating a new struct instance using values from an existing instance?

Struct update syntax.

Tuple Structs

Rust also supports tuple structs. These are like tuples but have names. They are useful when you want to give a tuple a name and make it distinct from other tuples, but the fields themselves don't need names.

rust
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
// You can access fields by index
println!("Black R component: {}", black.0);

Tuple structs are useful for creating distinct types from simple tuples, preventing accidental misuse.

Unit-Like Structs

You can also define structs that have no fields. These are called unit-like structs. They are useful when you need to implement a trait on a type but don't have any data to store. They behave like a unit type.

rust
struct AlwaysEqual;
let subject = AlwaysEqual;
// You can use subject in contexts where a type is needed, but it holds no data.

Learning Resources

The Rust Programming Language - Structs(documentation)

The official Rust book provides a comprehensive and authoritative guide to defining and using structs, covering syntax, instantiation, and field access.

Rust Structs Explained: A Deep Dive(tutorial)

This tutorial offers a practical, step-by-step approach to understanding Rust structs, including examples of defining, instantiating, and using them.

Rust by Example - Structs(documentation)

A collection of runnable examples demonstrating various aspects of Rust, including the definition and usage of structs.

Understanding Rust Structs and Enums(video)

A video tutorial that breaks down Rust structs and enums, explaining their purpose and how to implement them with clear visual aids.

Rust Structs: A Comprehensive Guide(blog)

This blog post delves into the intricacies of Rust structs, covering their definition, instantiation, methods, and common use cases.

Structs in Rust - GeeksforGeeks(blog)

GeeksforGeeks provides a clear explanation of Rust structs, including syntax, instantiation, and access methods, with illustrative code examples.

Rust Programming Language - Structs with Methods(documentation)

This section of the Rust book explains how to define methods associated with structs, enhancing their functionality.

Rust Struct Update Syntax Explained(video)

A short video specifically demonstrating and explaining the utility of the struct update syntax in Rust.

Rust Tuple Structs(tutorial)

TutorialsPoint offers a focused guide on Rust's tuple structs, explaining their creation and usage.

Rust Unit-Like Structs(blog)

This resource explains the concept and application of unit-like structs in Rust, which are structs with no fields.