In Rust, structs are custom data types that allow you to name and group multiple related values into a cohesive unit. This is particularly useful for building complex data structures. Defining structs is commonly used to represent the properties of an object, such as a user's name and age.
How to Define Structs
Structs in Rust are defined using the struct keyword. Here is a simple example defining a Person struct with two fields: name and age:
ruststruct Person { name: String, age: u8, }
This struct contains two fields: name and age. name is of type String, used for storing the person's name; age is of type u8 (an unsigned 8-bit integer), used for storing the person's age.
How to Create Struct Instances
Once defined, you can create instances of the struct. Here is an example of creating a Person struct instance:
rustlet person = Person { name: String::from("Alice"), age: 30, };
In this example, we create a variable named person that is an instance of the Person struct. We set the name field to "Alice" and the age field to 30.
How to Access Struct Fields
After creating a struct instance, you can access any field's value using dot notation (.). For example, to print the person's name and age, you can do:
rustprintln!("Name: {}, Age: {}", person.name, person.age);
Struct Methods
You can also define methods for structs. Methods are functions defined in the context of the struct. Here is an example of adding a method to the Person struct that returns a boolean indicating whether the person is an adult:
rustimpl Person { fn is_adult(&self) -> bool { self.age >= 18 } }
In this example, the is_adult method checks if the Person instance's age field is greater than or equal to 18. If so, it returns true; otherwise, it returns false.
You can now call this method on a Person instance:
rustlet person = Person { name: String::from("Alice"), age: 30, }; println!("Is Alice an adult? {}", person.is_adult());
This will output: Is Alice an adult? true.
By following these basic steps, you can effectively define and use structs in Rust. This makes data management more modular and clear.