Lesson 1.6 · 12 min
Giving code a name
Every step of Chatterbox sits in one long list inside main. That is fine for three lines and hopeless for three hundred. A function lets you give a few steps a name, so main can say banner() and mean "the first line", and you have been using them since lesson 1.3 without writing one. Time to write your own.
Adds to Chatterboxbanner() and greeting() become functions.
Compiler errors you will meet E0061
A name for some steps
You already know one function: main, the one every program starts in. And the exercises since lesson 1.3 each had another, like summary() or farewell(name), which you filled in without being told what a function really is. Here it is.
A function is a list of steps with a name. Writing fn, a name, brackets and a body in braces defines it: it writes the recipe down, and does nothing else. Writing the name with brackets, like print_banner(), calls it: the program jumps into the function, does its steps, and then comes back to exactly where it was and carries on.
$ cargo run
Chatterbox v0.1
Type a message and I will answer.
(main carries on here)
Chatterbox v0.1
Type a message and I will answer.The function is written above main. What is the first line this program prints?
hellostartend
Reveal the answer
The program prints: start A program always starts at main, wherever main is in the file. Defining greet above it only writes the recipe down; nothing in it runs until line 7 calls it. So the output is start, hello, end. Functions can even be written below main: the order in the file does not matter to the compiler.
Inputs and outputs
A function that does the same thing every time is useful. One that you can hand something to is far more useful. Inputs go inside the brackets, and each is written name: Type. Such an input is called a parameter, and the value you give it at the call is called an argument.
For a greeting the input is the person's name, so the parameter is name: &str. &str is the type of text the function can read, without taking it: the caller still has it afterwards. The type is required. Rust never guesses at a function's edges, so you, and the compiler, can tell how to use a function from its first line alone.
The output comes after an arrow: -> String is a promise that the function hands back a String, a piece of text it made itself. (Chapter 2 explains the difference between the two kinds of text. Here, read &str as "text coming in to be read" and String as "new text going out".) Step through a call and watch it happen.
Step through the program. Solid arrows are ownership; dashed arrows are borrows. Use ← → or the slider.
- Line 5. The program starts in main. main is the only function running.
- Line 6. greeting("Sam") is a call. A new box opens for greeting on top of main, and its parameter name holds the argument, "Sam". main waits, halfway through line 6.
- Line 2. The body runs. format! builds the text Hi Sam! I'm Chatterbox. This line has no semicolon, so its value is the answer greeting hands back.
- Line 3. greeting ends. Its box closes and its name goes with it. The answer travels back to the exact spot in line 6 that asked for it.
- Line 6. main is running again, and println! prints the answer. stdout:
Hi Sam! I'm Chatterbox. - Line 7. A second call: a fresh box for greeting, and this time name holds "Ada". Nothing is left over from the first call.
- Line 3. The same steps, with a different input, give a different answer. The box closes again.
- Line 7. main prints the second answer. stdout:
Hi Ada! I'm Chatterbox. - Line 8. main ends, and with it the program.
Why the last line has no semicolon
This is the most important idea in the lesson, and it runs through all of Rust. Code comes in two shapes:
- An expression works something out and produces a value.
2 + 3is an expression whose value is 5."Sam"is an expression whose value is that text.format!(…)andgreeting("Sam")are expressions too: each produces aString. - A statement is a step that does something and produces no value. Putting a semicolon after an expression turns it into a statement: the work is still done, and the value is thrown away.
println!("hi");is a statement: it prints, and there is nothing to keep.
A function body is a list of statements, optionally followed by one last expression with no semicolon. That last expression is the body's value, and so it is what the function hands back. In greeting, the format! line is that last expression. If a body has no last expression, its value is (), an empty value that means "nothing", and that only fits a function with no arrow. Two exceptions, so the rule stays true: a function can also hand a value back from any line with return value; (useful for leaving early, and you will see it later), and todo!(), which you will meet in the exercise below, is a placeholder that stops the program instead of producing a value, so the compiler accepts it under any arrow. So what happens if you add one innocent semicolon?
Does this compile — and if it does, does it run?
- It compiles and runs
- Compile error E0308
- Compile error E0061
Reveal the answer
It does not compile: E0308. The semicolon turns the format! line into a statement, so the text is built and then thrown away. The body ends with no last expression, so its value is (). The arrow promised a String: expected String, found (), which is E0308 from lesson 1.5. The compiler even points at the semicolon and suggests removing it.
error[E0308]: mismatched types --> src/main.rs:1:28 | 1 | fn greeting(name: &str) -> String { | -------- ^^^^^^ expected `String`, found `()` | | | implicitly returns `()` as its body has no tail or `return` expression 2 | format!("Hi {}! I'm Chatterbox.", name); | - help: remove this semicolon to return this value
The wrong number of inputs: E0061
A function's first line is a contract: greeting takes exactly one piece of text. A call has to match it, one argument for each parameter, in the same order. Forget the name and the compiler will not fill one in for you.
This is the exact output of the real compiler. Toggle the English, then pick a fix and see what actually happens.
error[E0061]: this function takes 1 argument but 0 arguments were supplied --> src/main.rs:6:20 | 6 | println!("{}", greeting()); | ^^^^^^^^-- argument #1 of type `&str` is missing | note: function defined here --> src/main.rs:1:4 | 1 | fn greeting(name: &str) -> String { | ^^^^^^^^ ---------- help: provide the argument | 6 | println!("{}", greeting(/* &str */)); | ++++++++++
E0061 in the compiler error atlas →
this function takes 1 argument but 0 arguments were supplied:greetingneeds one input and the call on line 6 gave it none.argument #1 of type `&str` is missing, next to the empty brackets: the first input, the piece of text, is the one missing.note: function defined hereshows the contract, line 1, with the parametername: &strunderlined, so you can see what the call should match.help: provide the argumentshows the call with/* &str */where an argument belongs. That is a gap for you to fill, not code to copy.
Fixes that were compiled for real
- Give it the name it asks for — compiles. One parameter, one argument. The call now matches the contract.
- Trap: give it two, to be safe — still E0061. Still E0061, now "takes 1 argument but 2 arguments were supplied". Too many is as wrong as too few: the compiler would not know what to do with the extra one.
- Change the contract instead: two parameters — compiles. If the function really does want two inputs, say so in its first line, separated by a comma, and every call passes two. This one lets the caller choose the bot's name as well.
Chatterbox v0.1, with functions
Chatterbox prints exactly what it printed after lesson 1.4. What changed is how main reads. The banner and the greeting each moved into a function of their own:
fn banner() -> Stringtakes no inputs and hands back the first line,Chatterbox v0.1, built withformat!.fn greeting(name: &str) -> Stringtakes the person's name and hands backHi Sam! I'm Chatterbox.with that name filled in.
Both bodies are a single last expression, with no semicolon. main now prints banner() and greeting("Sam") through a {} hole, then the same third line as before. The lines starting with /// are documentation comments: like //, the compiler skips them, but tools that build a description of a project show them as the description of the function underneath.
Chatterbox v0.1 Hi Sam! I'm Chatterbox. Type a message and I will answer.
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.
This is Chatterbox v0.1 with the bodies of banner and greeting replaced by todo!(), a placeholder that compiles but stops the program if it is ever reached. Write both bodies so the hidden tests pass: the banner is Chatterbox v0.1, and the greeting is Hi Sam! I'm Chatterbox. for the name "Sam", with any other name filled in the same way. Mind the last-line semicolon.
This is Chatterbox v0.1 with the bodies of banner and greeting replaced by todo!(), a placeholder that compiles but stops the program if it is ever reached. Write both bodies so the hidden tests pass: the banner is Chatterbox v0.1, and the greeting is Hi Sam! I'm Chatterbox. for the name "Sam", with any other name filled in the same way. Mind the last-line semicolon.
Hidden tests (4): an_empty_name_is_still_filled_in the_banner greets_whoever_it_is_given greets_sam
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
What you have now
Chapter 1 is done. You can make and run a Rust project, print text with holes, read what the compiler tells you, and write functions that take inputs and hand back answers. Chatterbox v0.1 has a banner and a greeting, each with a name of its own.
Next, chapter 2: the things a program remembers, starting with giving values names, so "Chatterbox" stops being typed in two places.
Say it out loud, then reveal
What is the difference between defining a function and calling it?Reveal
fn name() { … }) writes the steps down and runs nothing. Calling (name()) runs the steps, then comes back to the line that called it.What do the parts of <code>fn greeting(name: &str) -> String</code> mean?Reveal
&str (text it reads), that hands back a String.Why does the last line of a function body have no semicolon?Reveal
What does E0061 tell you?Reveal
That is lesson 1.6. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
How do I write a function in Rust?
Write fn, a name, the inputs in brackets with a type for each, then an arrow and the type that comes out, then the body in curly braces. For example: fn greeting(name: &str) -> String.
How do I return a value from a Rust function?
Make the value the last line of the body and leave the semicolon off. That last expression is what the function hands back. There is also a return keyword for leaving a function early.
What is the difference between an expression and a statement in Rust?
An expression produces a value, like 2 + 3 or a function call. A statement does something and produces no value. A semicolon after an expression turns it into a statement.
What does error E0061 mean in Rust?
E0061 means a function was called with the wrong number of arguments. The message says how many it takes and how many were given, and points at where the function is defined.
What is the difference between a parameter and an argument?
A parameter is the named input in the function definition, such as name. An argument is the actual value passed in a call, such as "Sam".