Trait Objects
Lesson 38 of 48 in Coddy's Rust for C Developers course.
A generic parameter chooses a concrete type for each instantiation. A trait object instead refers to a value whose concrete type is hidden behind a shared behavior. &dyn Trait borrows such a value; Box<dyn Trait> owns it on the heap. A vector of boxes can hold different concrete types that implement the same trait. Calls use dynamic dispatch, much like C context pointers paired with a table of callbacks. A simple trait with borrowed receivers and concrete return types supports this use. Generic methods can prevent a trait from being used as a trait object.
C
#include <stdio.h>
struct Sensor { const void *context; int (*read)(const void *); };
struct Fixed { int value; };
struct Difference { int high; int low; };
int fixed_read(const void *p) { return ((const struct Fixed *)p)->value; }
int difference_read(const void *p) { const struct Difference *d = p; return d->high - d->low; }
int main(void) {
struct Fixed f = {7}; struct Difference d = {9, 4};
struct Sensor sensors[] = {{&f, fixed_read}, {&d, difference_read}};
printf("%d\n", sensors[0].read(sensors[0].context) + sensors[1].read(sensors[1].context));
return 0;
}Rust
trait Sensor { fn read(&self) -> i32; }
struct Fixed(i32);
struct Difference(i32, i32);
impl Sensor for Fixed { fn read(&self) -> i32 { self.0 } }
impl Sensor for Difference { fn read(&self) -> i32 { self.0 - self.1 } }
fn main() {
let sensors: Vec<Box<dyn Sensor>> = vec![Box::new(Fixed(7)), Box::new(Difference(9, 4))];
let sum: i32 = sensors.iter().map(|s| s.read()).sum();
println!("{}", sum);
}A vector has one element type. Different concrete implementers fit together only after conversion to a common trait-object type.
Challenge
EasyDefine adjuster::Adjuster with apply(&self, value: i32) -> i32. Implement it for offset::Offset { pub amount: i32 }, which adds its amount, and ceiling::Ceiling { pub maximum: i32 }, which returns the smaller of the value and maximum. pipeline::run(value: i32, steps: &[Box<dyn Adjuster>]) -> i32 applies every supplied object once in slice order, passing each result to the next object. An empty pipeline returns its input. solve reads an initial integer followed by complete add amount or cap maximum pairs. Build owned trait objects and return the final value. All inputs and intermediate results fit i32.
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, adjuster.rs, offset.rs, ceiling.rs, pipeline.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 adjuster;
mod offset;
mod ceiling;
mod pipeline;
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 adjuster::Adjuster;
assert_eq!(offset::Offset { amount: -7 }.apply(19), 12);
assert_eq!(ceiling::Ceiling { maximum: 14 }.apply(22), 14);
assert_eq!(ceiling::Ceiling { maximum: 14 }.apply(-3), -3);
struct Times(i32);
impl adjuster::Adjuster for Times { fn apply(&self, v: i32) -> i32 { v * self.0 } }
let steps: Vec<Box<dyn adjuster::Adjuster>> = vec![Box::new(offset::Offset { amount: 4 }), Box::new(Times(3)), Box::new(ceiling::Ceiling { maximum: 32 })];
assert_eq!(pipeline::run(5, &steps), 27); assert_eq!(pipeline::run(8, &steps), 32);
assert_eq!(pipeline::run(5, &steps), 27);
assert_eq!(pipeline::run(-91, &[]), -91);
// 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