rust struct
Rust Struct
In Rust, a struct is a data structure that allows you to group together multiple related values into a single compound value. It is similar to a class in other programming languages. Here is an example of how to define a struct in Rust:
struct Person {
name: String,
age: u32,
is_employed: bool,
}
In this example, we define a struct called Person
with three fields: name
, age
, and is_employed
. The name
field is of type String
, the age
field is of type u32
(an unsigned 32-bit integer), and the is_employed
field is of type bool
(a boolean value).
To create an instance of the Person
struct and initialize its fields, you can use the following code:
let person = Person {
name: String::from("John"),
age: 30,
is_employed: true,
};
In this code, we create a variable called person
of type Person
and initialize its fields with the specified values.
You can access the fields of a struct using dot notation, like this:
println!("Name: {}", person.name);
println!("Age: {}", person.age);
println!("Is Employed: {}", person.is_employed);
This will print the values of the name
, age
, and is_employed
fields of the person
struct.
That's a brief overview of how to define and use a struct in Rust. Let me know if you have any further questions.