Start learning free

LESSON 609 OF 642 · OBJECT-ORIENTED PROGRAMMING

Pay Everyone in Rust

Practice

You write three kinds of workers and a function that pays them all.

Rust has no classes. As in the polymorphism lesson, the common type is a trait. Worker has one method, fn pay(&self) -> i32.

Each kind of worker is a struct that implements Worker:

  • HourlyWorker keeps a rate and hours. It earns rate × hours.
  • SalariedWorker keeps a monthly salary. It earns monthly.
  • Intern keeps a stipend. It earns stipend.

Then write payroll(workers). It gets the workers as a &Vec<Box<dyn Worker>>. It returns the sum of every worker's pay.

Get each pay by calling pay(). Never check which type a worker is.

That is polymorphism. One call runs each worker's own pay.

The tests also use a fourth kind, Contractor. The tests write it, not you. It has its own pay(). So your payroll pays it too.

The starter code already has the structs and their new functions. For each test, the harness builds the workers and prints payroll(workers).

 

Example 1:

Input: HourlyWorker::new(20, 40), SalariedWorker::new(3000), Intern::new(500)
Output: 4300
Explanation: The hourly worker earns 20 × 40 = 800.
The salaried worker earns 3000.
The intern earns 500.
In total, 800 + 3000 + 500 = 4300.

Example 2:

Input: HourlyWorker::new(25, 10), Contractor { fee: 1200 }
Output: 1450
Explanation: The hourly worker earns 25 × 10 = 250.
The contractor's own pay() returns 1200.
In total, 250 + 1200 = 1450.

Example 3:

Input: no workers
Output: 0
Explanation: An empty team costs nothing.

 

Constraints:

  • 0 to 100 workers.
  • Each rate is a whole number from 1 to 1,000.
  • Each number of hours is from 0 to 200.
  • Each monthly salary is from 1 to 100,000.
  • Each stipend is from 0 to 100,000.
  • Each contractor's pay is from 0 to 100,000.
STEP 1 OF 6
    Ctrl + Enter to check

    Pay Everyone in Rust

    Keep going with Rust500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free