Lesson 1.3 · 7 min
Printing and comments
Chatterbox is a program that talks, so the first thing to learn is how a Rust program says things. You will fill holes in text, leave notes for yourself, and meet the compiler telling you off for the first time.
Adds to ChatterboxChatterbox prints a banner.
Holes in the text
You can print fixed text, but a chat program mostly prints text that depends on something. println! lets you leave a hole {} in the text and give it the value to put there, after a comma.
$ cargo run
Chatterbox says hello to youWhat does this print?
2 + 3 = 55{} + {} = {}
Reveal the answer
The program prints: 2 + 3 = 5 The holes are filled left to right: the first {} gets 2, the second gets 3, the third gets the result of 2 + 3. Numbers print just like text.
Notes for yourself
Anything after // on a line is a comment. The compiler skips it completely. Comments are for the next person who reads the code, and that person is usually you in a month.
$ cargo run
Chatterbox v0.1Text you keep instead of printing
Sometimes you want the finished text as a value, not on the screen yet. format! works exactly like println!, but hands you the text back instead of printing it. You will use it in the exercise below.
The compiler has opinions
Now the useful part. What happens if you use something the program has never heard of?
error[E0425]: cannot find value `user` in this scope --> src/main.rs:2:28 | 2 | println!("Hello, {}!", user); | ^^^^ not found in this scope
Read the error from the top. "cannot find value user in this scope" means: you used the word user, and nothing in the program has given that word a meaning. The arrows in the message point at the exact spot. The code in brackets, E0425, is the error's ID. You can look any ID up, and this course keeps a list of them.
The fix is to give user a value first. That is the next chapter. For now just notice: the program did not run at all. The compiler caught it before anything printed.
Chatterbox should open with a banner such as Chatterbox v0.1. Fill in the one blank so banner() returns that text. You do not need to understand fn yet (chapter 3 explains it): just fill the blank.
Chatterbox should open with a banner such as Chatterbox v0.1. Fill in the one blank so banner() returns that text. You do not need to understand fn yet (chapter 3 explains it): just fill the blank.
Hidden tests (3): has_name_and_version is_not_empty starts_with_the_name
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
Say it out loud, then reveal
What does {} do inside println!?Reveal
What does the compiler do with a // comment?Reveal
What does "cannot find value in this scope" tell you?Reveal
That is lesson 1.3. Tick it off so the course remembers where you are.
Sources Rust by Example: formatted print