go · level 1 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a recipe card with a name on top.
A function is a set of instructions wrapped up under one name. Write the recipe once, then cook it as often as you like, without copying a line. You have been writing one all along: main!
To a function, write func, a name, empty brackets and a block: func cheer() {. Defining it does not run it. It only writes the recipe card.
To it, write its name with brackets, like cheer(). Every line inside then runs, top to bottom. Go reads the whole file first, so a function can sit above or below main.
package main
import "fmt"
func cheer() {
fmt.Println("Go team!")
fmt.Println("You can do it!")
}
func main() {
cheer()
cheer()
} Go starts every program by calling main for you, while your other functions wait to be called.
guess first
The function comes after main. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
fmt.Println("Ready?")
wave()
}
func wave() {
fmt.Println("Hello there!")
}
your turn
Your turn. Write your own chant.
Pick a name for your function and type it in all three name blanks. Put any words you like between the quotes, then run it.
output
press run to see what happens
fix it
The dog will not bark. Can you fix it?
output
press run to see what happens
- The function is written perfectly. Look inside
main, where you try to use it. - Writing a function's name on its own does not call it. Something is missing after the name.
- Add brackets after bark inside
main, so it says bark(), then run.
nailed it
you wrote your very own command. :D
- A function is a set of instructions with a name.
- Define it with
func, a name, brackets and a block. - Call it with its name and brackets.
new words in your collection
- function
- define
- call
This lesson isn’t saved. A free account remembers every lesson you finish.