Menu
CoddyTech

Trait Objects

Lesson 38 of 48 in Coddy's Rust for Go Developers course.

Go interface values hold a dynamic type and value and allow calls through that interface. A Rust trait object such as &dyn Speak similarly supports dynamic dispatch, but Rust still makes ownership explicit. The reference borrows an existing object; Box<dyn Speak> would own a heap-allocated object.

A generic T: Speak uses a concrete type parameter; a trait object erases the concrete type behind a pointer and dispatches through its method table. Only dyn-compatible traits can form trait objects. Methods returning Self without the required restrictions or generic methods can prevent ordinary object use; the borrowed string-returning method here is compatible.

Borrowed trait objects have lifetimes too. A borrowed object cannot outlive its referent, and an owned Box still has lifetime constraints for any references inside its value. Go typed-nil interface pitfalls do not translate into nullable Rust shared references.

Complete Go comparison program:

package main
import "fmt"
type Speak interface { Speak() string }
type Cat struct{}
func (Cat) Speak() string { return "mew" }
type Bird struct{}
func (Bird) Speak() string { return "chirp" }
func main() { xs := []Speak{Cat{}, Bird{}}; for _, x := range xs { fmt.Println(x.Speak()) } }

Go output:

mew
chirp

Complete Rust teaching program:

trait Speak { fn speak(&self) -> &'static str; }
struct Cat;
struct Bird;
impl Speak for Cat { fn speak(&self) -> &'static str { "mew" } }
impl Speak for Bird { fn speak(&self) -> &'static str { "chirp" } }
fn main() {
    let cat = Cat;
    let bird = Bird;
    let xs: [&dyn Speak; 2] = [&cat, &bird];
    for x in &xs { println!("{}", x.speak()); }
}

Rust output:

mew
chirp
challenge icon

Challenge

Easy

Define 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));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Go Developers

Practice on your own: Online Rust compiler