What is a Struct
What is a structure?
A user-defined data type made up of variables with various data types is called a structure. The struct keyword must come before the structure name in order to define a structure. The curly brackets surround structural members. Structure members, usually referred to as fields, are declared with their type and name inside curly brackets.
The Syntax of structure:
struct Student
{
member-variable1;
member-variable2;
.
.
}
The term struct is used in the syntax above to define structure. Different types of variables are contained in a structure.
How to declare the instance of a structure
let user = Student{
// key:value pairs;
}
A user in the aforementioned statement is an instance of the Student structure. The structural name is used to define it, followed by curly brackets. The data that we wish to save in the key field is represented by the value of the key:value pairs enclosed in curly brackets.
Let's create a structure of employee:
struct Employee{
employee_name : String,
employee_id: u64,
employee_profile: String,
active: bool,
}
An Instance of employee structure:
let employee = Employee{
employee_name : String::from("Akshay Gupta"),
employee_id: 12,
employee_profile : String::from("Computer Engineer"),
active : true,
};
How to access a specific member variable of Structure?
Dot notation is a useful tool for accessing a structure’s individual member variable. If we were to wish to retrieve the employee_name variable from an Employee structure, it would seem as follows:
employee.employee_name;
Note: If we want to change the value of a particular field by using dot notation, then we have to make an instance mutable as Rust does not allow a particular field as mutable.
let mut employee = Employee{
employee_name : String::from("Akshay Gupta"),
employee_id: 12,
employee_profile : String::from("Computer Engineer"),
active : true,
};
employee.employee_name = String :: from("Akhil Gupta");
Creating an instance within the function body:
fn create_employee(name:String, profile:String)
{
Employee{
employee_name:name,
employee_id:12,
employee_profile:profile,
active:true,
}
}
Within the function body of the aforementioned example, an implicit instance of employee structure is generated. The Employee structure instance with the specified name and profile is returned by the create_employee() function.
When fields and parameters provided to the function have the same name, use the Field Init Shorthand.
When a variable and a field have the same name, Rust gives you the option to use field init shorthand. Fields and variables don’t need to be repeated.
fn create_employee(employee_name:String, employee_profile:String)
{
Employee{
employee_name,
employee_id:12,
employee_profile,
active:true,
}
}
The parameters and fields have the same names in the example above. As a result, employee_name can be written directly without the requirement to write employee_name:employee_name.