Rust Struct
In Rust, a struct is a composite data type that allows you to group together values of different types into a single entity. You can think of a struct as a way to define your own custom data type.
Here's an example of a struct:
struct Person { name: String, age: u32, is_student: bool, } let person1 = Person { name: String::from("Alice"), age: 30, is_student: false, }; println!("Name: {}", person1.name); println!("Age: {}", person1.age); println!("Is student: {}", person1.is_student);
In this example, we're defining a struct called Person
that has three fields: name
of type String
, age
of type u32
, and is_student
of type bool
. We're then creating an instance of the Person
struct called person1
and initializing its fields with values.
We can access the fields of a struct using the dot notation, as shown in the println!
statements.
You can define methods on a struct using the impl
keyword. Here's an example:
struct Person { name: String, age: u32, is_student: bool, } impl Person { fn greet(&self) { println!("Hello, my name is {} and I am {} years old.", self.name, self.age); } } let person1 = Person { name: String::from("Alice"), age: 30, is_student: false, }; person1.greet();
In this example, we're defining a method called greet
on the Person
struct using the impl
keyword. The greet
method takes a reference to self
(i.e., the instance of the Person
struct) and prints a greeting using the values of the name
and age
fields.
We're then creating an instance of the Person
struct called person1
and calling the greet
method on it using the dot notation.
Structs are a powerful tool in Rust that can be used to create custom data types with meaningful field names and behavior.