loading

Update Syntax

utilizing the structural update syntax to create a new instance from existing instances.

The struct update syntax can be used when a new instance utilizes the majority of the values from an old instance. Think about Employee 1 and Employee 2, two employees.

Create the employee1 instance of the employee structure first:

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

Create the employee2 instance second. The employee2 object shares some values with the employee1 instance. The employee2 instance can be declared in two different ways.

Declaring the employee2 instance without updating the syntax is the first method.

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

Using a syntax change to declare the employee2 instance is the second method.

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

The remainder of the fields are not explicitly set and have the same value as the fields in the supplied instance, as indicated by the phrase “…”

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
				
			

The base and height of a right-angled triangle are the two variables that make up the triangle structure in the example above. Within the main() method, a Triangle instance is generated.

Share this Doc

Update Syntax

Or copy link

Explore Topic