Defining Functions

As a program grows, the same few lines often show up in many places. A function helps with this. It is a block of code with a name. You write the block once, and then you run it by its name whenever you need it.

You have already written one function in every program: main. Here is a program with a second function, printLine:

package main

import "fmt"

func printLine() {
	fmt.Println("----------")
}

func main() {
	fmt.Println("Order 1")
	printLine()
	fmt.Println("Order 2")
	printLine()
}

Output:

Order 1
----------
Order 2
----------

The keyword func starts a function. After it come the name, a pair of parentheses (), and the body in curly braces { }. It is the same shape as main.

The line printLine() inside main is a call. When the program reaches a call, it jumps into the function and runs its body. Then it comes back and goes on with the line after the call. main calls printLine two times, so the dashes are printed two times.

Go always starts a program at main. Every other function runs only when some code calls it.

Above or below main

In Go, you can write a function above main or below it. Go reads the whole file before it runs anything, so it already knows every function name. This program puts printLine at the bottom, and it works the same way:

package main

import "fmt"

func main() {
	fmt.Println("Order 1")
	printLine()
}

func printLine() {
	fmt.Println("----------")
}

Output:

Order 1
----------

A name Go does not know

If you spell a name wrong in a call, the program does not compile:

package main

import "fmt"

func printLine() {
	fmt.Println("----------")
}

func main() {
	printLne()
	fmt.Println("Order 1")
}

Output:

# command-line-arguments
./main.go:10:2: undefined: printLne

undefined means Go has no function or variable with that name. 10:2 is the line and the column of the mistake. Fix the spelling and the program runs.

Giving a function a value

printLine does the same thing every time. Often you want a function to work with a value that changes from call to call. For that, you put a parameter inside the parentheses. A parameter is a variable that gets its value from the call:

package main

import "fmt"

func greet(name string) {
	fmt.Println("Hello,", name)
}

func main() {
	greet("Alice")
	friend := "Bob"
	greet(friend)
}

Output:

Hello, Alice
Hello, Bob

name string means that greet takes one string value and calls it name inside its body. The value you put in the call is called an argument. In greet("Alice"), the argument is "Alice", so name is "Alice" during that call. The argument can also be a variable: greet(friend) gives name the value of friend, which is "Bob".

A parameter can have any type. For a number, write something like func showAge(age int). The next lesson shows functions with more than one parameter, and functions that send a value back.

In the exercise, complete printFee so it prints the fee for a distance, and then call it from main with the distance that main reads.