Start learning free

LESSON 659 OF 679 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Employees and Managers

Practice O(1)

A company pays every employee a salary. A manager is an employee too, but earns a bonus on top of the salary. Rust has no class inheritance: as in the lesson Inheritance, a Manager holds an Employee in a field and forwards calls to it, and the behavior both share lives in a trait, Worker.

Write the trait Worker:

  • get_name(&self) -> &str and pay(&self) -> i32, which each type writes for itself;
  • describe(&self) -> String, with a default body written once, in the trait: it returns the text <name> earns <pay>, where the amount is what self.pay() returns, for example Ana earns 3000. Every type that implements Worker gets this describe unchanged, and inside it self.pay() runs that type's own pay.

the struct Employee:

  • its fields name and salary, and Employee::new(name, salary);
  • in impl Worker for Employee: get_name returns the name, pay returns the salary.

and the struct Manager:

  • its fields employee, the Employee inside it, and bonus, and Manager::new(name, salary, bonus), which builds the inner employee with Employee::new;
  • in impl Worker for Manager: get_name forwards to the inner employee, and pay returns the inner employee's pay plus the bonus. That call, self.employee.pay(), is how Rust calls "the parent's version": it is what knows how an employee is paid.

The input is a list of people, one per line: employee name salary or manager name salary bonus. For each line, the code that tests your types creates that value with Employee::new or Manager::new and prints what its describe() returns, on a line of its own.

 

Example 1:

Input:
    employee Ana 3000
    manager Bob 4000 1000
Output:
    Ana earns 3000
    Bob earns 5000
Explanation:
Ana's pay is her salary. Bob's pay is the inner employee's pay, his salary 4000, plus his bonus 1000.
Bob's describe() is the trait's default describe(), but the pay() it calls is Manager's.

Example 2:

Input:
    manager Cleo 5000 0
    employee Dan 5000
Output:
    Cleo earns 5000
    Dan earns 5000
Explanation: A manager whose bonus is 0 earns exactly the salary, like an employee.

Example 3:

Input:
    manager Eve 7000 2500
    employee Finn 2800
    employee Gus 3100
    manager Hana 6000 500
Output:
    Eve earns 9500
    Finn earns 2800
    Gus earns 3100
    Hana earns 6500
Explanation: Employees and managers come in any order, and each value keeps its own name and numbers.

 

Constraints:

  • 0 <= salary <= 106
  • 0 <= bonus <= 106
  • A name is one word of 1 to 20 English letters. Two people may have the same name.
  • At most 100 people per test case.
STEP 1 OF 11
    Ctrl + Enter to check