Trait Objects
Lesson 38 of 48 in Coddy's Rust for Java Developers course.
Java interface-typed variables commonly refer to runtime-selected implementations. Rust offers trait objects such as &dyn Voice for dynamic dispatch when the concrete implementing type is hidden behind a reference. The reference carries access to the value and information needed to dispatch through the trait. Box<dyn Voice> can own a dynamically sized trait value through an allocation, but using a trait object does not inherently require Box.
By contrast, fn speak<T: Voice>(x: &T) uses a generic type parameter, normally specialized at compile time for its concrete instantiations. A trait must satisfy dynamic-compatibility rules to be used as a trait object; for example, arbitrary generic methods cannot be dispatched this way without restrictions. A shared trait-object reference also has a borrow lifetime. It does not keep a short-lived owner alive like a Java reference would.
Java: complete program
class Main {
interface Voice { String call(); }
static class Owl implements Voice { public String call() { return "hoot"; } }
public static void main(String[] args) {
Voice voice = new Owl();
System.out.println(voice.call());
}
}Rust: complete program
trait Voice { fn call(&self) -> &'static str; }
struct Owl;
impl Voice for Owl { fn call(&self) -> &'static str { "hoot" } }
fn main() {
let owl = Owl;
let voice: &dyn Voice = &owl;
println!("{}", voice.call());
}Pitfall: dyn Trait and generic T: Trait are different dispatch and representation choices, not alternate spellings for inheritance.
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 Java 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