Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Structs in Rust

What are Structs?

Structs, short for structures, are custom data types in Rust that allow you to group related data together. They enable you to create complex data types by combining multiple simple data types. Structs are particularly useful in scenarios where you want to model real-world entities.

Defining a Struct

To define a struct in Rust, you use the struct keyword followed by the name of the struct and its fields. Each field has a name and a type. Here is an example of a struct definition for a Person:

struct Person { name: String, age: u32, }

In this example, the Person struct has two fields: name of type String and age of type u32.

Creating Instances of Structs

Once you have defined a struct, you can create instances of it by providing values for its fields. Here’s how you can create an instance of the Person struct:

let person1 = Person {
name: String::from("Alice"),
age: 30,
};

In this code, we create a new instance person1 of the Person struct with the name "Alice" and age 30.

Accessing Struct Fields

You can access the fields of a struct using dot notation. Here’s how you can access the fields of person1:

println!("Name: {}", person1.name);
println!("Age: {}", person1.age);

This will print the name and age of person1 to the console.

Tuple Structs

Rust also supports a special kind of struct called a tuple struct, which is similar to a regular tuple but has a name. Tuple structs are defined without field names but rather by their types. Here’s an example:

struct Color(u32, u32, u32); // Represents RGB values

You can create an instance of this tuple struct like this:

let black = Color(0, 0, 0);

Unit-Like Structs

Unit-like structs are structs that do not have any fields. They are useful when you need to implement a trait for a type without any associated data. Here’s an example:

struct Unit;

Conclusion

Structs in Rust provide a way to create custom data types that can model complex data structures. They are foundational to Rust programming and enable you to create highly organized and maintainable code. Understanding how to define, create, and manipulate structs is essential for any Rust programmer.