Rust program to return a structure from the function (Structure Example)

Rust | Structure Example: Write a program to return a structure from the function.
Submitted by Nidhi, on October 27, 2021

Problem Solution:

In this program, we will create an Employee structure. Then we will create a function to compare the salaries of employees and return the object of the employee, who is earning more salary.

Program/Source Code:

The source code to return a structure from the function is given below. The given program is compiled and executed successfully.

// Rust program to return a structure 
// from the function

struct Employee {
   eid:u32,
   name:String,
   salary:u32
}

fn printEmployee(emp:&Employee){
   println!("  Employee ID    : {}",emp.eid );
   println!("  Employee Name  : {}",emp.name);
   println!("  Employee Salary: {}\n",emp.salary); 
}

fn compareEmpSalary(emp1:Employee, emp2:Employee)->Employee{
    if emp1.salary>emp2.salary{
        return emp1;
    }
    else{
        return emp2;
    }
}

fn main() {
   let emp1 = Employee{
        eid: 101,
        name: String::from("Lokesh Singh"),
        salary:50000
   };
   
   let emp2 = Employee{
        eid: 102,
        name: String::from("Mukesh Kumar"),
        salary: 48000
   };
   
   println!("Employee Information");
   printEmployee(&emp1);    
   printEmployee(&emp2);   
   
   println!("\n\nEmployee, who is earning more:");
   let emp3 = compareEmpSalary(emp1,emp2);
   printEmployee(&emp3);   
}

Output:

Employee Information
  Employee ID    : 101
  Employee Name  : Lokesh Singh
  Employee Salary: 50000

  Employee ID    : 102
  Employee Name  : Mukesh Kumar
  Employee Salary: 48000


Employee, who is earning more:
  Employee ID    : 101
  Employee Name  : Lokesh Singh
  Employee Salary: 50000

Explanation:

In the above program, we created a structure Employee and three functions printEmployee(), compareEmpSalary(), main(). The Employee structure contains three members eid, name, and salary.

The printEmployee() function is used to print employee information. The compareEmpSalary() function is used to compare the salaries of two specified employees and return the employee, who is earning more salary.
In the main() function, we created two objects of structure. Then compare created objects and print the result.

Rust Structures Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.