Search⌘ K
AI Features

Grouping Data with Structs

Explore how to use structs in Rust to group related data such as visitor names and greetings, making code easier to manage. Learn to define structs, create constructors, and implement methods to handle data effectively in your game development projects.

The treehouse bouncer would like both a name and a customized greeting for every visitor. We could create a new array for greetings, but we’d need to be careful to add every visitor and their greetings in the same order. That would quickly become tricky to maintain. A better approach is to store all the information about a guest together in a struct.

Struct

A struct is a type that groups data together. Structs contain member fields variables of almost any type. Grouping data together makes it easier to access complicated information.

Once we’re looking in the right struct, individual pieces of data are available by name. Structures are ubiquitous in Rust: String and StdIn are both struct types. Rust’s struct types combine related data and can implement functionality for that type. They’re similar to class types in other languages.

We can define our own structures Structures are a type, just like i32, String and ...