Rust Program: Calculate employee annual salary
Rust Structs and Enums: Exercise-7 with Solution
Write a Rust program that defines a struct Employee with fields id, name, and salary. Now write a function to calculate an employee's annual salary.
Sample Solution:
Rust Code:
// Define a struct named 'Employee' with fields: id, name, and salary
struct Employee {
id: u32,
name: String,
salary: f64,
}
// Define a function to calculate the employee's annual salary
fn calculate_annual_salary(employee: &Employee) -> f64 {
// Assuming there are 12 months in a year
employee.salary * 12.0
}
fn main() {
// Create an employee instance
let employee = Employee {
id: 101,
name: String::from("Merrill Jamal"),
salary: 61000.0,
};
// Calculate the employee's annual salary using the function
let annual_salary = calculate_annual_salary(&employee);
// Print the employee's annual salary
println!("Employee {}'s (id = {}) annual salary : ${:.2}", employee.name, employee.id, annual_salary);
}
Output:
Employee Merrill Jamal's (id = 101) annual salary : $732000.00
Explanation:
Here is a brief explanation of the above Rust code:
- struct Employee { ... }: Defines a struct named "Employee" with fields 'id', 'name', and 'salary'.
- fn calculate_annual_salary(employee: &Employee) -> f64 { ... }: Defines a function named calculate_annual_salary that takes a reference to an "Employee" instance as a parameter and returns a 'f64' representing the employee's annual salary. Inside the function, the monthly salary is multiplied by 12 to get the annual salary.
- fn main() { ... }: This is the entry point of the program.
- Inside main():
- An "Employee" instance named 'employee' is created with sample details.
- The "calculate_annual_salary()" function is called with a reference to the 'employee' instance to calculate the annual salary.
- The calculated annual salary is printed using println! macro.
Rust Code Editor:
Previous: Rust Program: Define result Enum.
Next: Rust Program: Enum Colors.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/basic/rust-structs-and-enums-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics