Lesson 5.2 · 8 min
Giving a struct behaviour
A Message can hold an author and a text, but everything you do with one still lives in loose functions. An impl block puts the actions next to the data they act on.
Adds to ChatterboxMessage methods, and /shout.
Functions that live with the struct
In lesson 5.1 you wrote record(log, msg), a loose function that takes a borrowed &Message. An impl block lets you attach functions like that to the type itself, so they are called with a dot: msg.shout(). Same borrowing rules as chapter 4; just a tidier address.
Two kinds of thing go in an impl. A function without self, like new, is called on the type: Message::new(..). The :: is the same path separator as in String::from: it reads "the new that belongs to Message". Rust calls this an associated function. A function whose first parameter is self is a method, called on a value.
$ cargo run
HELLO THERE
false&self is shorthand for "borrow this message, read only". Inside the method, self.text is the field. The caller keeps the key, which is why you can call shout and then is_empty on the same m.
A method that needs to change the message says &mut self, the exclusive borrow from lesson 4.5.
error[E0596]: cannot borrow `m` as mutable, as it is not declared as mutable --> src/main.rs:18:5 | 18 | m.clear(); | ^ cannot borrow as mutable | help: consider changing this to be mutable | 17 | let mut m = Message::new("you", "oops"); | +++
E0596: "cannot borrow m as mutable, as it is not declared as mutable". Calling clear quietly takes a &mut borrow of m, and you never said m could change. The fix is the same word as in lesson 2.2: let mut m.
So the signature is a promise you can read from outside. &self: looks only. &mut self: may change it. self with no &: the method receives the key itself, so the caller has given the message away and cannot use it afterwards (the move from lesson 4.3).
What does this print?
HIHIhiHIHIit does not compile
Reveal the answer
The program prints: HIHIhi shout borrows with &self and returns a brand-new String. The original m.text is untouched and m is still usable, so you can call it as often as you like.
Chatterbox v0.5: Message grows methods, and /shout
Here is the whole program after this lesson, with the new lines in green. Message gets an impl block with three functions:
Message::new("you", message)builds a message from two borrowed pieces of text. The loop used to spell outMessage { author: String::from("you"), … }twice; now it says what it means in one short call.to_line(&self)turns a message into one transcript line,you: hello.recordnow just asks the message for its line instead of gluing the pieces together itself.shout(&self)returns the text in capitals, a brand-newString. All three only look, so none of them needs&mut self.
And Chatterbox learns a new command. /shout hello there takes the words after the command (with rest_of, from lesson 4.6), wraps them in a Message just long enough to call .shout() on it, and prints the result. The help text lists it too.
Sam /shout hello there /quit
Chatterbox v0.5 What should I call you? Hi Sam! I'm Chatterbox. Ask me anything. bot: HELLO THERE bot: bye, Sam! messages so far: 0
Show the whole program (open it after you have tried the exercise below: it contains the answer)
Download this version (zip)Unzip, then cargo run inside the folder.
A small warm-up first, on a cut-down Message with only a text. It practises the one kind of method Chatterbox does not use yet, &mut self. Fill in both methods. word_count only looks and returns how many words are in the text: split_whitespace() splits text into words and .count() counts what it gives you. The count is a usize, a whole number used for sizes and positions. append changes the message: it adds a space and then the extra text to the end.
A small warm-up first, on a cut-down Message with only a text. It practises the one kind of method Chatterbox does not use yet, &mut self. Fill in both methods. word_count only looks and returns how many words are in the text: split_whitespace() splits text into words and .count() counts what it gives you. The count is a usize, a whole number used for sizes and positions. append changes the message: it adds a space and then the extra text to the end.
Hidden tests (4): append_joins_with_a_space append_then_count counts_words empty_has_no_words
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
Now the real thing. This is the whole Chatterbox program with the bodies of Message::new, to_line and shout taken out. Put all three back. The hidden tests build messages, read their lines and shout them, including empty text and mixed capitals.
Now the real thing. This is the whole Chatterbox program with the bodies of Message::new, to_line and shout taken out. Put all three back. The hidden tests build messages, read their lines and shout them, including empty text and mixed capitals.
Hidden tests (7): new_fills_both_fields record_uses_the_line shout_handles_mixed_case shout_leaves_the_message_alone shout_of_nothing_is_nothing to_line_is_author_colon_text to_line_with_empty_text
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
Say it out loud, then reveal
What is the difference between <code>Message::new(..)</code> and <code>m.shout()</code>?Reveal
new has no self, so it is called on the type and builds a value. shout takes &self, so it is called with a dot on a value that exists.Why did <code>m.clear()</code> fail with E0596?Reveal
clear needs &mut self, an exclusive borrow, and m was not declared mut.What does <code>&self</code> promise the caller?Reveal
That is lesson 5.2. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
What is an impl block in Rust?
An impl block holds the functions that belong to a type. Writing impl Message { ... } attaches those functions to Message, so you can call them with a dot or with Message::.
What is self in a Rust method?
self is the value the method was called on. &self borrows it to read, &mut self borrows it to change, and plain self takes ownership of it.
What is the difference between a method and an associated function?
A method has self as its first parameter and is called on a value, like m.shout(). An associated function has no self and is called on the type, like Message::new().
What does error E0596 mean in Rust?
You tried to change something, or borrow it with &mut, that was not declared mutable. Add mut where the variable is made, as in let mut m.