Coding for All
Lesson 23: Functions
Functions Write your own function and call it twice.
1package main
2
3import "fmt"
4
5func wave() {
6 fmt.Println("Hello!")
7 fmt.Println("How are you?")
8}
9
10func main() {
11 wave()
12 wave()
13}
Terminal
$ go run main.go
Hello!
How are you?
Hello!
How are you?
Every line, explained
package main
Every Go file starts by saying which package it belongs to. package main means "this is a program you can run", and Go will look inside it for func main.
import "fmt"
import brings in a package from Go's standard library. "fmt" (short for format) is the one full of printing tools, like fmt.Println.
func wave() {
func defines a function: a named block of code. Functions live at the top level of the file, next to main (never inside it). Go doesn't care about their order, but putting helpers first reads nicely top-to-bottom.
fmt.Println("Hello!")
fmt.Println(...) prints what is inside the brackets to the terminal, then moves to a new line (Println is short for "print line"). The capital P matters: in Go, the tools a package shares all start with a capital letter. Part of the wave function's body.
fmt.Println("How are you?")
fmt.Println(...) prints what is inside the brackets to the terminal, then moves to a new line (Println is short for "print line"). The capital P matters: in Go, the tools a package shares all start with a capital letter. Also part of the body: the function prints two lines every time it runs.
}
This } closes the function.
func main() {
func main() { ... } is where a Go program starts. When you run the program, Go finds func main inside package main and runs everything between its braces, top to bottom.
wave()
Writing the function's name with round brackets calls it: Go jumps up into wave, runs its body, then comes back here.
wave()
Calling it again runs the body again. Write once, use as many times as you like. That is the whole point of functions!
}
This closing brace } ends func main.