Lesson 8.4 · 12 min
One name for anything that replies
Today Chatterbox answers with an echo. In the next chapter a real model will answer instead, and the chat loop should not care which. A trait is how Rust says "anything that can reply". With one, Chatterbox gets a /model command that swaps who answers while you chat.
Adds to ChatterboxA Replier trait, and /model to swap who answers.
A promise with a name
Right now the bot's answer comes from a function called reply in main.rs: it echoes your words. In the next chapter the answer will come from a real model over the internet. A chat loop that says "call the echo function" would have to be rewritten for the model. A chat loop that says "ask whatever replies" would not.
A trait is a list of things a type can do, with a name. It is a promise: any type that implements the trait has these methods. Chatterbox's trait is called Replier and promises two methods:
name(&self) -> &str: a short name, likeecho, for the banner and for/model.reply(&self, history: &[Message]) -> String: the answer to the conversation so far. It is handed the whole history as&[Message], a borrowed view of a list, the way&stris a borrowed view of text (lesson 8.3 used&[T]). Here the list is the historyVec, with the newest message last. The echo only looks at the last message, but a real model needs all of it, so the promise says so from the start.
Inside the trait block each method is only a first line ending in ;, with no body. The trait says what; each type that implements it says how.
The ability a generic can ask for
In lesson 8.3, last_n<T> worked for any T at all, because it never asked a T to do anything: it only counted and sliced. Most generic code is not that lucky. A function that wants to ask something for a reply needs a T that can reply. A trait is how it says so: T: Replier reads "any type T, as long as T keeps the Replier promise". That extra condition is called a trait bound. Here is a small example, separate from Chatterbox, with two types that keep the promise and one generic function that uses it.
What is the second line this program prints?
pretend -> (pretend model) I read: hiecho -> you said: hipretend -> you said: hi
Reveal the answer
The program prints: pretend -> (pretend model) I read: hi The second call hands ask a Pretend, so T is Pretend and both r.name() and r.reply(msg) run Pretend's own versions. Inside ask, the bound is what made those two calls allowed at all.
Read impl Replier for Echo as "here is how Echo keeps the promise". Now hand a function something that never made the promise. A function can also accept "anything that implements Replier" by taking &dyn Replier, a borrow of some replier whose exact type is not fixed. Either way, the compiler checks the promise.
What happens when this program is compiled?
- It compiles and runs
- Compile error E0277
- It compiles, then panics
Reveal the answer
It does not compile: E0277. E0277 is "the trait bound is not satisfied". Mute never wrote impl Replier for Mute, so it cannot be used where a Replier is expected. This is checked before the program ever runs.
error[E0277]: the trait bound `Mute: Replier` is not satisfied --> src/main.rs:12:10 | 12 | talk(&Mute, "hello"); | ^^^^^ unsatisfied trait bound | help: the trait `Replier` is not implemented for `Mute` --> src/main.rs:5:1 | 5 | struct Mute; | ^^^^^^^^^^^ help: this trait has no implementations, consider adding one --> src/main.rs:1:1 | 1 | trait Replier { | ^^^^^^^^^^^^^ = note: required for the cast from `&Mute` to `&dyn Replier`
Fixed while compiling, or chosen while running
Chatterbox has to choose who answers while it runs, because you can type /model pretend in the middle of a chat. A generic cannot do that. For ask<T>, the compiler writes a separate copy of the function for each type it is called with, and at every call the type is already decided. And a plain variable cannot change kind: once it holds an Echo, its type is Echo forever.
This is the exact output of the real compiler. Toggle the English, then pick a fix and see what actually happens.
error[E0308]: mismatched types --> src/main.rs:23:15 | 21 | let mut replier = Echo; | ---- expected due to this value 22 | println!("{}", replier.name()); 23 | replier = Pretend; | ^^^^^^^ expected `Echo`, found `Pretend`
E0308 in the compiler error atlas →
mismatched types: the variable is anEcho, and you tried to put aPretendin it.expected `Echo`, found `Pretend`:let mut replier = Echo;fixed the type on that first line.mutlets the value change, never the type.- Both types implement
Replier, and the compiler still says no: to the compiler a promise two types share does not make them the same type.
Fixes that were compiled for real
- Put it in a Box<dyn Replier> — compiles. The variable now holds a box that points at some Replier on the heap. Swapping puts a new box in, and the old one is dropped. This is what Chatterbox does.
- Borrow it as &dyn Replier — compiles. Also works when both values live somewhere else for long enough. Chatterbox builds its repliers on the spot inside /model, so it needs a Box that owns the value.
- Trap: box it without dyn — still E0308. <code>Box<Echo></code> is a box that can only ever hold an Echo. The <code>dyn Replier</code> part is what says "any Replier".
A Box is a pointer (a small value that says where another value lives) to a value it owns on the heap (lesson 4.1). dyn means "some type that implements this trait, decided while the program runs". Echo and Pretend can be different sizes, and a variable needs one size, but the box is always the same size whatever is inside it: so Box<dyn Replier> can hold either, and the next one too.
How does replier.name() know whose name to run? A pointer to a dyn value is two pointers: one to the value, and one to a small table of that type's methods, called a vtable. Each call looks up the method in the table first. That lookup is the small price of choosing at run time; a generic pays nothing at run time, because each copy calls its type's method directly. Try both below.
Switch between the two tabs and make a call with each kind of replier.
With a generic, ask::<Echo> and ask::<Pretend> are two separate copies of the function in the finished program, and each call jumps straight to the right one. With dyn Replier there is one function; the pointer it is given carries a second pointer to the vtable for Echo or for Pretend, and each call looks the method up there.
Chatterbox gets repliers
All of this lives in a new module, replier.rs. Two types keep the promise:
Echois the oldreplyfunction moved into a type. The length limit it read from the constantMAX_LENis now its one field,max_len, filled in fromMAX_LENwhen an Echo is made. Itsreplytakes the last message withhistory.last(), which gives anOption(lesson 5.4) because a history can be empty, and answers exactly as before.Pretendis a stand-in for a real model. It has no fields at all (pub struct Pretend;), and its answer proves it was handed the whole conversation: it says how many messages it read.
Here is what changed in main.rs, all green below:
let mut replier: Box<dyn Replier> = Box::new(Echo { max_len: MAX_LEN });starts with the echo. The banner now says who replies,Chatterbox v0.8 (replies by: echo), and the oldreplyfunction is gone frommain.rs. Its two tests are not thrown away: they moved with it intoreplier.rs, asecho_repeats_youandecho_refuses_long_messages, next to a new one forPretend. The safety net from lesson 7.3 comes along with the code it guards.- For a chat line, your message goes into the history first, then
replier.reply(&history)is asked for an answer, which is printed and pushed too. The loop never knows which kind of replier it is talking to. /againasks with a one-message slice made on the spot,&[Message::new("you", text)].use replier::{Echo, Pretend, Replier};brings the trait in as well as the two types. Rust only lets you call a trait's methods where the trait's name is in scope.
command.rs gets a Model(String) variant, built with need like /say, and HELP lists /model <echo|pretend>. In main, the Model arm matches on choice.as_str(), which borrows the String as a &str so it can be compared with text in quotes. It builds an Option<Box<dyn Replier>>: a new box for a name it knows, None for anything else. With Some(r), replier = r; swaps the box. The old box loses its owner and is dropped right there (chapter 4's one-owner rule doing the tidying). The history on disk does not change: store.rs still writes one author: text line per message, as in lesson 8.2.
Sam hi /model pretend still there /model banana /model echo back /quit
Chatterbox v0.8 (replies by: echo) What should I call you? Hi Sam! I'm Chatterbox. Ask me anything. bot: you said: hi bot: replies now come from pretend bot: (pretend model) I read all 3 messages. You last said: still there bot: I don't know a model called banana. Try echo or pretend bot: replies now come from echo bot: you said: back bot: bye, Sam! messages so far: 3 saved 6 messages to chatterbox.log
Show the whole program (open it after you have tried the exercise below: it contains the answer)
src/message.rsunchanged
src/store.rsunchanged
Download this version (zip)Unzip, then cargo run inside the folder.
Read the run. The first answer is the echo. After /model pretend, the next answer says it read all 3 messages: your hi, the echo's answer, and still there. That is the whole history arriving through &history. /model banana is a name nobody knows, so nothing changes. /model echo swaps back. The chat loop did not change once.
This is the whole Chatterbox program with the body of Pretend's reply taken out. Put it back. For a history ending in c with 3 messages it answers (pretend model) I read all 3 messages. You last said: c; with exactly one message it says 1 message, not 1 messages; and for an empty history (pretend model) nothing to read yet.
This is the whole Chatterbox program with the body of Pretend's reply taken out. Put it back. For a history ending in c with 3 messages it answers (pretend model) I read all 3 messages. You last said: c; with exactly one message it says 1 message, not 1 messages; and for an empty history (pretend model) nothing to read yet.
Hidden tests (4): an_empty_history_has_nothing_to_read one_message_is_enough pretend_reads_the_whole_history the_name_is_pretend
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
If you have coded before
In Python you would write a class with a reply method and rely on "if it quacks, it is a duck". A Protocol or abstract base class makes the promise explicit. A Rust trait is that, enforced by the compiler: calling reply on something that never made the promise does not compile. Box<dyn Replier> is closest to what every Python variable already is: a reference to some object, with the method looked up when it is called.
What you have now
Chatterbox v0.8 has a Replier trait, two types that keep it, and a /model command that swaps between them while you chat. The chat loop only ever holds a Box<dyn Replier>. The next lesson changes no code: it answers a question left open since first_word in lesson 4.6. Then, as a preview, chapter 9 adds a third replier that is not pretending: it sends the history to a real model.
Say it out loud, then reveal
What is a trait?Reveal
impl Trait for Type keeps the promise.What does <code>T: Replier</code> add to a generic function?Reveal
What does <code>Box<dyn Replier></code> mean, and why does Chatterbox need it instead of a generic?Reveal
What error appears when you pass a type that does not implement the trait?Reveal
That is lesson 8.4. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
What is a trait in Rust?
A set of method signatures that different types can implement. It is Rust's way of describing shared behaviour, similar to an interface in other languages.
What is the difference between generics with a trait bound and dyn Trait?
A generic with a bound, like T: Replier, is turned into one copy of the code per type when the program is compiled, so the type is fixed at each call. dyn Trait, usually behind a Box or a reference, lets the concrete type be chosen while the program runs, at the cost of looking each method up in a small table.
Why do I need Box for a trait object?
Different implementors have different sizes and a variable needs one size. A Box is a pointer, which always has the same size, to the value on the heap.
Why can I not call a trait method even though the type implements it?
The trait itself has to be in scope where you call the method. Add a use line that names the trait, as Chatterbox does with use replier::Replier.