ADVERTISEMENT
ADVERTISEMENT

Rust program to define a method in a struct

Rust | Structure Example: Write a program to define a method in a struct.
Submitted by Nidhi, on October 27, 2021

Problem Solution:

In this program, we will create an Employee structure. Then we will define a method in the structure by implementing the structure using the impl keyword.

Program/Source Code:

The source code to define a method in a struct is given below. The given program is compiled and executed successfully.

// Rust program to define a method 
// in a struct

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

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

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

   emp.printEmployee();
}

Output:

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

Explanation:

In the above program, we created a structure Employee and function main(). The Employee structure contains id, name, and salary. And, we implemented the printEmployee() method inside the structure using the impl keyword.

In the main() function, we created the object of employee structure and printed the employee information.

Rust Structures Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.