Learn/Go/6. Functions
Lesson 6 of 15
Sign in

Go, lesson 6

Functions

A function is a named piece of code you can run whenever you need it. Functions let you give a name to an idea ("convert to Fahrenheit"), reuse it, and test it on its own. You have already written one: main.

Declaring a function

A declaration starts with func, then the name, the parameters in parentheses, and the result type. Each parameter has a name followed by its type.

return hands a value back to the caller and leaves the function immediately. A function with a result type must return on every path; the compiler checks this.

When several parameters in a row share a type, you can write the type once:

A function with no result simply leaves out the type. It can still use a bare return to stop early.

Functions can be declared in any order in the file. main can call a function that appears below it.

Multiple return values

A Go function can return more than one value. List the types in parentheses. This is used everywhere in the standard library, most often to return a result together with an error.

2 exercises to try what you just read.

Exercise 1

Lowest and highest

Press Ctrl Enter or Check to test your code.

Exercise 2

Letter grades

Press Ctrl Enter or Check to test your code.

If you only need one of the results, put _ in place of the other: q, _ := divmod(17, 5).

Arguments are copies

Go passes arguments by value: the function receives its own copy. Changing a parameter inside the function does not change the caller's variable.

To get a changed value back, return it: x = doubled(x). Later lessons show pointers, which let a function change the caller's data directly.

Scope

A variable is visible only inside the block ({ ... }) where it is declared, from that line onward. Variables declared inside a function are local: each call gets fresh ones, and they disappear when the function returns. Variables declared outside every function, at package level, are visible to all functions in the package. Prefer local variables and parameters; they make it obvious where data comes from.

If an inner block declares a variable with the same name as an outer one, the inner one shadows it until the block ends. This is legal but easy to trip over, especially with :=, so choose distinct names.

Functions are values

A function can be stored in a variable or passed to another function. You will use this for sorting in lesson 12. An anonymous function is written inline:

Further reading

  • A Tour of Go: Functions
  • A Tour of Go: Multiple results
  • Effective Go: Functions

Write a function minMax(a, b, c int) (int, int) that returns the smallest and the largest of three numbers. In main, read three integers and print the two results separated by a space. Try to solve it with if statements rather than the built-in min and max.

Sample input:

Sample output:

Write a function grade(score int) string that turns a test score into a letter: A for 90 and above, B for 80–89, C for 70–79, D for 60–69 and F below 60. In main, read scores until the input runs out and print score: letter for each one.

Sample input:

Sample output:

func toFahrenheit(c float64) float64 {
	return c*9/5 + 32
}

func main() {
	fmt.Println(toFahrenheit(100)) // 212
}
func area(width, height int) int {
	return width * height
}
func greet(name string) {
	if name == "" {
		return
	}
	fmt.Println("Hello,", name)
}
func divmod(a, b int) (int, int) {
	return a / b, a % b
}

func main() {
	q, r := divmod(17, 5)
	fmt.Println(q, r) // 3 2
}
func double(n int) {
	n = n * 2 // changes only the local copy
}

x := 4
double(x)
fmt.Println(x) // still 4
square := func(n int) int { return n * n }
fmt.Println(square(6)) // 36
8 3 11
3 11
95 72 40
95: A
72: C
40: F