HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to GoVariablesData TypesOperatorsStringsArray & SliceMap (Dictionary)Conditions (if / switch)Loops (for)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & Slice
🗂️ Map
🔁 Condition & Loop
🧩 Function
Go›Functions

Functions

Definition with func, parameter/return types, and multiple return values.

Simple enough for a 5-year-old to understand

func and return

Parameter type comes AFTER the name, and the return type comes after the parentheses.

Example code
1
package main
2
import "fmt"
3
func square(x int) int {
Takes an int, returns an int.
FunctionTakes an int, returns an int.
4
return x * x
Result.
FunctionResult.
5
}
6
func main() {
7
fmt.Println(square(5))
25
Output / Input25
8
}
FunctionOutput / Input
💡 Hint: Functions are defined outside of main, at the package level.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Write a function named addUp that takes two ints and returns their sum; print addUp(8, 9).

🎯 Expected output: 17

Loading editor…

About this topic

The most distinctive feature of Go functions is that they can return MULTIPLE VALUES. This is the foundation of the language's error-handling philosophy: a function returns the result and the error together, and the caller checks the error. There is no exception mechanism in Go, and this is a deliberate choice.

An error in Go is not a special language construct but an ordinary value. Therefore, you can store it in a variable, pass it to a function, and wrap it. In return, you have to write every error check by hand, and Go code tends to be filled with these checks.

The defer keyword postpones the execution of a call until the function finishes. It is used for closing files, releasing locks, and cleaning up resources; it eliminates the risk of forgetting by allowing you to write the cleanup code right next to the opening statement.

What you will learn

  • Defining functions and writing types
  • Returning multiple values
  • The error return pattern
  • Named return values
  • Doing cleanup with defer
  • Accepting a variable number of arguments

When to use?

When you write a function that returns an error, the error is the LAST return value — this is not just a convention, it is almost a universal rule and meets the reader's expectation.

defer is written immediately wherever you open a resource. If there are multiple defers, they execute in reverse order; meaning the last deferred runs first.

Common mistakes

Wrong

func divide(a, b int) int {
	return a / b
}
fmt.Println(divide(10, 0))

Division by zero crashes the program with "panic: runtime error: integer divide by zero". Since there is no exception catching in Go, operations that can fail MUST RETURN an error.

Correct

func divide(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("division by zero")
	}
	return a / b, nil
}

Wrong

func process() error {
	f, _ := os.Open("data.txt")
	data := make([]byte, 100)
	f.Read(data)
	return nil
}

Two mistakes were made: because Open's error was ignored, f becomes nil when the file isn't opened, and Read causes a panic; additionally, the file is NEVER CLOSED and a file descriptor leaks on every call. The error must be checked and it should be closed with defer.

Correct

func process() error {
	f, err := os.Open("data.txt")
	if err != nil {
		return err
	}
	defer f.Close()
	data := make([]byte, 100)
	_, err = f.Read(data)
	return err
}

Wrong

func getValue() (int, error) {
	return 5
}

Since the function declares that it returns two values, it is mandatory to return both; otherwise you get a "not enough return values" error. If there is no error, explicitly return nil.

Correct

func getValue() (int, error) {
	return 5, nil
}

Frequently asked questions

Why is there no exception mechanism in Go?

Design choice: exceptions make control flow invisible, and which line can throw an error is not explicitly written in the code. Go keeps the flow transparent by making the error an ordinary value. The cost is writing every check by hand.

When exactly does defer run?

When the function returns — both on a normal return and in the event of a panic. Multiple defers run in reverse order. This guarantee makes resource cleanup reliable: no matter how many return paths there are, defer runs.

When is panic used?

Almost never. panic is for situations where it is pointless for the program to continue — like a broken programming assumption. Errors are returned for predictable errors; using panic in library code is considered bad practice.

Summary

Go functions return multiple values and the error is the last return value; there is no exception mechanism, and every error is checked manually. defer allows you to write the cleanup right next to the opening and runs regardless of the return path.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code