Traits and Contracts
Lesson 36 of 48 in Coddy's Rust for C++ Developers course.
A C++ abstract interface can specify virtual operations, while templates can rely on available expressions without a common base. A Rust trait specifies a contract that types implement explicitly. It may provide default methods built from required methods. Implementing a trait does not add a base-class subobject, and traits do not provide inherited instance fields. Calls can use static or dynamic dispatch depending on the surrounding API, so declaring a trait alone does not choose virtual dispatch. Method-call syntax may require the trait to be in scope. The named-person example builds a greeting from an observer; it does not implement the exercise's charging rules. When porting an interface, separate shared behavior from shared storage and use composition for state that several objects need.
Complete standalone C++17 program:
#include <iostream>
#include <string>
struct Named {
virtual ~Named() = default;
virtual std::string name() const = 0;
std::string greeting() const { return "Hello " + name(); }
};
struct Person : Named {
std::string name() const override { return "Lin"; }
};
int main() { Person p; std::cout << p.greeting() << '\n'; }Complete standalone Rust program:
trait Named {
fn name(&self) -> &str;
fn greeting(&self) -> String { format!("Hi {}", self.name()) }
}
struct Person { name: String }
impl Named for Person { fn name(&self) -> &str { &self.name } }
fn main() {
let p = Person { name: "Ada".to_string() };
println!("{}", p.greeting());
}Challenge
EasyDefine charge::Charge with required cost(&self, units: i32) -> i32 and default pair(&self, first: i32, second: i32) -> i32, which calls cost for each argument and adds the results. In separate modules, implement the trait for flat::Flat { pub fee: i32 } and per_unit::PerUnit { pub rate: i32 }. A flat charge is zero for zero units and the fee otherwise; a per-unit charge is the rate times units. All units, fees, and rates are nonnegative. solve reads mode amount first second, where mode is flat or unit and the three integers are at most 1000. Return the first cost, second cost, and pair cost separated by spaces.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, charge.rs, flat.rs, per_unit.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod charge;
mod flat;
mod per_unit;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
use charge::Charge;
let f = flat::Flat { fee: 19 }; let u = per_unit::PerUnit { rate: 7 };
assert_eq!(f.cost(0), 0); assert_eq!(f.cost(11), 19); assert_eq!(f.pair(0, 8), 19);
assert_eq!(u.cost(6), 42); assert_eq!(u.cost(0), 0); assert_eq!(u.pair(3, 8), 77);
struct CustomCharge;
impl charge::Charge for CustomCharge { fn cost(&self, units: i32) -> i32 { units * units + 2 } }
let custom = CustomCharge;
assert_eq!(custom.pair(3, 5), 38); assert_eq!(custom.pair(0, 0), 4);
assert_eq!(f.pair(2, 3), 38);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for C++ Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap2Decisions and Loops
Boolean ConditionsIf ExpressionsMatch and EnumsLoops and RangesRecap: Charge Gate8Traits and Generic Code
Traits and ContractsGenerics and BoundsTrait ObjectsFunction PointersDerived Value SemanticsTesting Public ContractsScoring Contracts Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler