Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Defining Structs in Rust

What are Structs?

In Rust, a struct (short for "structure") is a custom data type that lets you create complex data types by combining multiple values. Structs are used to create a meaningful grouping of related data. Each piece of data in a struct is called a field, and each field can be of a different type.

Defining a Struct

To define a struct in Rust, you use the struct keyword followed by the name of the struct and the fields enclosed in curly braces. The fields consist of a name and a datatype.

Example:

struct Person {

name: String,

age: u32,

}

In this example, we define a struct named Person with two fields: name of type String and age of type u32.

Creating Instances of Structs

After defining a struct, you can create instances of it by specifying values for each field. This is done using the struct name followed by the field names and values enclosed in curly braces.

Example:

let person1 = Person {

name: String::from("Alice"),

age: 30,

};

Here, we create an instance of Person named person1, initializing the name field with "Alice" and the age field with 30.

Accessing Struct Fields

You can access the fields of a struct instance using dot notation. This allows you to retrieve or modify the values stored in the fields.

Example:

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

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

In this example, we print the name and age fields of the person1 instance to the console.

Using Tuple Structs

Rust also allows you to define tuple structs, which are similar to regular structs but do not require field names. Instead, they use types to define the structure.

Example:

struct Color(u32, u32, u32);

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

In this example, we define a tuple struct Color with three u32 values representing RGB color values, and we create an instance called black.

Conclusion

Structs are a powerful feature in Rust that allow you to define custom data types. By grouping related data together, structs help you model complex systems effectively. Whether you use regular structs or tuple structs, understanding how to define and use them is essential for building Rust applications.