An online shop offers three ways to ship a parcel. Standard shipping is the basic one. Express and Economy are kinds of shipping too: they answer the same two questions, what the option is called and what it costs, but each in its own way. Rust has no class inheritance; as in the lesson Method Overriding, the parent's behavior is a trait with default methods, and a type replaces a default by writing its own method in its impl block.
Write the trait Shipping, whose default methods are the standard option:
name(&self) -> &strreturns"Standard".cost(&self, weight: i32) -> i32returns5 + weight: a base price of 5, plus 1 for each kilogram.
Standard implements Shipping with an empty block, impl Shipping for Standard {}, so it keeps both defaults. Then write the two types that replace both methods:
Express:namereturns"Express", andcostreturns10 + 2 * weight.Economy:namereturns"Economy", andcostreturns3 + weight / 2, where the division rounds down:7 / 2is3.
The input lists parcels, one per line: the option (standard, express or economy) and the weight. For each line, the code that tests your types creates that option, keeps it as a Box<dyn Shipping>, and prints <name>: <cost> from its name() and cost(weight). The calls are the same for every option; each type answers with its own method, or with the trait's default where it has none.
Example 1:
Input:
standard 4
express 4
economy 4
Output:
Standard: 9
Express: 18
Economy: 5
Explanation: The same parcel of 4 kilograms costs 5 + 4 = 9 with Standard, 10 + 2 * 4 = 18 with Express
and 3 + 4 / 2 = 5 with Economy.
Example 2:
Input:
standard 0
express 0
economy 0
Output:
Standard: 5
Express: 10
Economy: 3
Explanation: With a weight of 0, only the base prices are left.
Example 3:
Input:
economy 7
economy 1
standard 7
express 7
Output:
Economy: 6
Economy: 3
Standard: 12
Express: 24
Explanation: Economy halves the weight and rounds down: 7 / 2 is 3, so 3 + 3 = 6, and 1 / 2 is 0, so 3 + 0 = 3.
Constraints:
0 <= weight <= 1000, a whole number of kilograms.- At most
100parcels per test case.
Free plan: 30 tutor messages. PRO is unlimited.
