Industrial Training




Update Syntax

Creating a new instance from other instances using Struct update syntax.
When a new instance uses most of the values of an old instance, then we can use the struct update syntax. Consider two employees employee1 and employee2.


    First, create the instance employee1 of Employee structure:

 let employee1 = Employee{  
employee_name : String::from("Akshay Gupta"),  
employee_id: 12,  
employee_profile : String::from("Computer Engineer"),  
active : true,  
};  

    Second, create the instance the employee2. Some values of the employee2 instance are the same as employee1. There are two ways of declaring the employee2 instance.

The first way is declaring the employee2 instance without syntax update.


 let employee2 = Employee{  
employee_name : String::from("Akhil Gupta"),  
employee_id: 11,  
employee_profile : employee1.employee_profile,  
active : employee1.active,  
};  

The second way is declaring the employee2 instance by using syntax update.


 let employee2 = Employee{  
employee_name : String::from("Akhil Gupta"),  
employee_id: 11,  
..employee1  
};  

The syntax '..' specifies that the rest of the fields are not explicitly set and they have the same value as the fields in the given instance.


Let's see a simple example of Structure:
 struct Triangle  
{  
base:f64,  
height:f64,  
}  
  
fn main()  
{  
let triangle= Triangle{base:20.0,height:30.0};  
print!("Area of a right angled triangle is {}", area(&triangle));  
}  
  
fn area(t:&Triangle)->f64  
{  
0.5 * t.base * t.height  
}  

Output:
Area of a right angled triangle is 300

In the above example, the structure of a triangle is created, and it contains two variables, i.e., base and height of a right-angled triangle. The instance of a Triangle is created inside the main() method.




Hi I am Pluto.