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) -> &strandpay(&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 whatself.pay()returns, for exampleAna earns 3000. Every type that implementsWorkergets thisdescribeunchanged, and inside itself.pay()runs that type's ownpay.
the struct Employee:
- its fields
nameandsalary, andEmployee::new(name, salary); - in
impl Worker for Employee:get_namereturns the name,payreturns the salary.
and the struct Manager:
- its fields
employee, theEmployeeinside it, andbonus, andManager::new(name, salary, bonus), which builds the inner employee withEmployee::new; - in
impl Worker for Manager:get_nameforwards to the inner employee, andpayreturns 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 <= 1060 <= bonus <= 106- A name is one word of 1 to 20 English letters. Two people may have the same name.
- At most
100people per test case.
Free plan: 30 tutor messages. PRO is unlimited.
