Structs
Using the struct
keyword, you can define custom data types in Rust applications or libraries.
Structs can have zero or more "fields." Each field has a name and a data type.
Basic Struct
Let's say you want to define a custom Rust struct that represents a dog. 🐕 We will define two fields on the struct that represent:
- The dog's breed, as a
String
value - The dog's age, as an unsigned 8-bit integer
u8
#![allow(unused)] fn main() { struct Dog { breed: String, age: u8, } }
Instantiate Struct
The struct
itself only defines the structure of an object, like a blueprint for a house or car.
In order to create an actual dog, we have to instantiate the struct.
To create a struct instance, we use curly braces after the struct name. Inside the curly braces, we specify field names, followed by the values to assign to each field.
#![allow(unused)] fn main() { let dog01 = Dog{ breed: "German Shepherd".to_string(), age: 9, }; let dog02 = Dog{ breed: "Border Collie".to_string(), age: 5, }; let dog03 = Dog{ breed: "Australian Shepherd".to_string(), age: 3, }; }
Tuple Structs
A special type of struct known as a tuple-based struct can have unnamed fields, rather than named fields. To access fields from a tuple, you would use the index number of the field, starting at 0, and incrementing by 1.
For example, let's say that you want to define a custom Person
type, with a few fields:
- First name
- Last name
- Year Born
#![allow(unused)] fn main() { struct Person(String, String, i16); }
To instantiate this tuple-based struct, simply use the following syntax.
#![allow(unused)] fn main() { let p1 = Person("Trevor".to_string(), "Sullivan".to_string(), 1984); }
You can access the last name field by using the index 1
, and the year born with 2
.
As you can see, these are still valid struct fields, but the fields don't have names, just indexes.
#![allow(unused)] fn main() { println!("Your last name is {} and were born in the year {}", p1.1, p1.2); }
Public Structs
If a struct needs to be accessible outside of a Rust module, use the pub
keyword to make it "publicly" visible.
By default, structs are private members of a module.
#![allow(unused)] fn main() { pub struct Person { first_name: String, } }
NOTE: Trailing commas are supported in Rust, but are not required.