How it works...

At some point of the product development life cycle, developers often have too many variables to handle and the code becomes really complex. This is where structs appear as a big savior. Structs enable developers to create complex data types, where they allow the unification of multiple data types under a single name.

In this recipe, we created a custom data type named Circle, which has two labels radius and x of the type f64, which is a 64-bit float type. Both the parameters here are related to the Circle data type and uniquely express their features.

Consider use cases such as database management, machine learning models, and so on, where the developer has to handle multiple variables conveying the property of a single task/entity. Structs, in these cases, are great tools to utilize for making the code more optimized and modular. This makes the life of a developer easy; we can debug errors easily and scale up features on requests of the application/product.

We use the struct keyword to create a user-defined data type, where the custom name is provided after the keyword but along with the types of the different labels or variables it uses.

In the main function, we initialized a mutable variable circle1 of the user-defined data type Circle and populated it with its required values, which are 10.0 for radius and 10.0 for x. We did this to access the variable in the scope of the program. We get the value by calling the variable name label we require, that is, we get the value of the assigned values by calling circle1.x and circle.radius.

We pass the reference of circle1 to get_radius, where we have an argument c1 of the data type Circle from which we get the radius of c1.radius. Then, we call the function with get_radius(&circle1) to get the value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.66.94