Grouping Data with Structs

Learn how to group data by using structs.

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 enumerations.
A type isn’t a variable, it’s a description of what variables of that type can contain. We can make one Visitor type, and then use it over and over again for different visitors known as an instance. This is another form of abstraction. Structs can be added above the main function in main.rs:

Note: Don’t worry about the warnings, we’ll use these variables later.

Get hands-on with 1400+ tech skills courses.