Q:

Rust program to pass a structure into function

belongs to collection: Rust Structures Programs

0

In this program, we will create a structure with few members. Then we will pass created a structure into the function to print the values of members.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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

// Rust program to pass a structure 
// into function

#[derive(Default)]

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

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

fn main() {
   let mut emp:Employee= Employee::default();
   
   emp.eid     = 101;
   emp.name    = String::from("Lokesh Singh");
   emp.salary  = 50000;
    
   printEmployee(emp);    
}

Output:

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

Explanation:

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

The printEmployee() function is used to print employee information.

In the main() function, we created the object of structure and initialized it with default values using the default() method. After that, we assigned values member-wise using the "." operator and printed the employee information.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust program to return a structure from the functi... >>
<< Rust program to create a structure and assign the ...