In Rust, a struct is a way to group related data together into a single, custom data type. You can create a struct using the ‘struct‘ keyword followed by the name of the struct and the fields the struct contains.
Here’s a simple example:
struct Person {
name: String,
age: u32,
is_student: bool,
}
In this example, we’re defining a ‘Person‘ struct with three fields: ‘name‘ of type ‘String‘, ‘age‘ of type ‘u32‘, and ‘is_student‘ of type ‘bool‘.
To create an instance of this struct, we can use the following syntax:
let person = Person {
name: String::from("Alice"),
age: 25,
is_student: true,
};
In this example, we’re creating a new ‘Person‘ instance and assigning it to the ‘person‘ variable. We’re using the curly brace syntax to specify the values for each field. Note that we’re using ‘String::from()‘ to create a new ‘String‘ object for the ‘name‘ field.
We can access fields of the struct using dot notation, like so:
println!("Name: {}", person.name);
println!("Age: {}", person.age);
println!("Is student: {}", person.is_student);
This will output:
Name: Alice
Age: 25
Is student: true
Overall, using structs is a powerful way to organize data and make your code more expressive in Rust.