Javatpoint Logo
Javatpoint Logo

What is a structure?

A structure is a user-defined data type that consists of variables of different data types. A structure is defined by using the struct keyword before the structure name. Structure members are enclosed within the curly brackets. Inside the curly brackets, structure members are defined with their name and type and structure members are also known as fields.

The Syntax of structure:

In the above syntax, structure is defined by using the keyword struct. A structure contains the variables of dissimilar types.

How to declare the instance of a structure

In the above declaration, a user is an instance of Student structure. It is defined by using the structure name and then curly brackets. The curly brackets contain key:value pairs where keys are the name of the fields and value is the data which we want to store in the key field.

Let's create a structure of employee:

An Instance of employee structure:

How to access a specific member variable of Structure?

We can access the specific member variable of a structure by using dot notation. Suppose we want to access the employee_name variable of an Employee structure, then it looks like:

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.

Creating an instance within the function body:

In the above example, an instance of Employee structure is created implicitly within the function body. The create_employee() function returns the instance of Employee structure with the given name and profile.

Using the Field Init Shorthand when parameters passed to the function and fields have the same name.

Rust provides the flexibility of using field init shorthand when both the variables and fields have the same name. There is no need of repetition of fields and variables.

In the above example, the name of parameters and fields are the same. Therefore, there is no need of writing employee_name:employee_name, it can be directly written as employee_name.

Next TopicUpdate Syntax

Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials