← Back to Go Course | Chapter 4: Functions | Lesson 1 of 7

Function Basics

A function is a labeled recipe you write once, so you can ask for it by name whenever you need that job done again.

Declaring a Function

A function is declared with the func keyword, a name, a parenthesized parameter list (each with a name and type), and an optional return type. The body runs whenever the function is called elsewhere in the program.

Example: Declaring a Function

markup
package main

import "fmt"

func square(n int) int {
	return n * n
}

func main() {
	fmt.Println(square(6))
}

Multiple Parameters

Functions can take several parameters, each declared with its own name and type, or grouped together when consecutive parameters share the same type to reduce repetition.

Note: Consecutive parameters sharing a type can omit the type on all but the last, e.g. 'func add(a, b int) int'.

Example: Multiple Parameters

markup
package main

import "fmt"

func rectangleArea(width, height float64) float64 {
	return width * height
}

func main() {
	fmt.Println(rectangleArea(4.5, 3.0))
}

Functions with No Return Value

A function that doesn't need to hand back a result simply omits the return type, and inside its body a bare return (or reaching the end of the function) exits it.

Example: Functions with No Return Value

markup
package main

import "fmt"

func logMessage(msg string) {
	fmt.Println("[LOG]", msg)
}

func main() {
	logMessage("server started")
}

Every Path Must Return

If a function's signature declares a return type, the Go compiler requires that every possible execution path through the function ends in a return statement -- an if without a matching else that also returns won't compile.

Example: Every Path Must Return

markup
package main

import "fmt"

func sign(n int) string {
	if n > 0 {
		return "positive"
	} else if n < 0 {
		return "negative"
	}
	return "zero"
}

func main() {
	fmt.Println(sign(-5))
}
Common Mistakes
  1. Forgetting that Go requires the parameter type after each name, and that consecutive same-typed parameters can share one type annotation.
  2. Trying to call a function before it's declared in the file -- unnecessary in Go, since order of top-level declarations doesn't matter, unlike some scripting languages.
  3. Not returning a value on every code path when the function signature declares a return type, which is a compile error.
Chapter Summary
  • Functions are declared with 'func name(params) returnType { }'.
  • Parameters of the same type can share a single type annotation.
  • Every code path in a function with a declared return type must return a value.
  • Top-level function order in a file doesn't matter -- Go resolves all declarations before running.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.