Skip to content
Skip to content
DocsGo LearningintermediateFunctions
Chapter 4 of 14·intermediate·7 min read

Functions

Hàm

Multiple returns, closures, variadic functions, and init

Hover or tap any paragraph to see Vietnamese translation

Function Declaration

Functions in Go are declared with the func keyword, followed by the function name, parameters in parentheses, return type, and the function body. Go allows shorthand syntax for consecutive parameters of the same type: instead of func add(x int, y int), you write func add(x, y int).

functions.go
1package main23import "fmt"45// Basic function declaration6func greet(name string) {7    fmt.Println("Hello, " + name)8}910// Function with return type11func add(a, b int) int {12    return a + b
Tip
Go does not support default parameters. Use variadic parameters or accept a custom struct to simulate default behavior.

Multiple Return Values

Go allows functions to return multiple values. This is how Go handles error handling naturally — instead of throwing exceptions, functions return a result value and an error value. By convention, the error is always the last return value and is typically nil when there is no error.

multiple_returns.go
1package main23import (4    "fmt"5    "strconv"6)78// Function returning multiple values: result and error9func divide(a, b float64) (float64, error) {10    if b == 0 {11        return 0, fmt.Errorf("division by zero")12    }

Named Return Values

Go allows you to name return values. These variables are initialized to the zero value of their type. A bare return statement returns the current named return values. This can make code more concise, but should be used sparingly in longer functions as it reduces clarity.

named_returns.go
1package main23import "fmt"45// Named return values6func minMax(arr []int) (min, max int) {7    if len(arr) == 0 {8        return9    }10    min, max = arr[0], arr[0]11    for _, v := range arr {12        if v < min {
Info
Use named return values sparingly. They are useful for short functions but reduce clarity in longer ones — use explicit returns instead.

Variadic Functions

Variadic functions accept a variable number of arguments of the same type. You specify this by placing ... before the final parameter type. Inside the function, the variadic parameter acts like a slice. You can also pass an existing slice to a variadic function using ....

variadic.go
1package main23import "fmt"45// Variadic function — accepts zero or more ints6func sum(nums ...int) int {7    total := 08    for _, n := range nums {9        total += n10    }11    return total12}

First-Class Functions

In Go, functions are first-class values. You can assign them to variables, pass them as arguments to other functions, and return them from functions. The type of a function includes its parameter types and return type.

first_class.go
1package main23import "fmt"45// Function type: takes two ints, returns an int6type Operation func(int, int) int78// Implement some operations9func add(a, b int) int {10    return a + b11}12

Closures — Capturing State

A closure is an anonymous function that encloses variables from its surrounding scope. Closures are often returned from factory functions. Each closure holds its own reference to the enclosed variables, creating independent state.

closures.go
1package main23import "fmt"45// makeCounter returns a closure that increments and returns a counter6func makeCounter() func() int {7    count := 08    return func() int {9        count++10        return count11    }12}

The init() Function

The init() function is a special function that runs automatically before main(). Go calls all init() functions in a package before any other code in that package runs. You can define multiple init() functions in the same file or different files — they run in the order determined by filename. Common use cases: registering database drivers, setting up configuration, validating requirements.

init.go
1package main23import (4    "fmt"5)67var (8    config map[string]string9    logFile string10)1112// First init (runs first alphabetically by file)
Warning
Go runs init() functions in order in the same file. If you have different files in the same package, the order is sorted by filename. Do not rely on exact order — if it matters, use an explicit setup function.

Anonymous Functions

Go allows you to define anonymous functions (without a name) and invoke them immediately. Anonymous functions are often passed as callbacks or to perform small tasks in a local context.

anonymous.go
1package main23import "fmt"45func main() {6    // Anonymous function invoked immediately7    func() {8        fmt.Println("Anonymous function executed immediately")9    }()1011    // Anonymous function with parameters12    func(name string, age int) {

Key Takeaways

Điểm Chính

  • Functions can return multiple values, making error handling naturalHàm có thể trả về nhiều giá trị, làm cho xử lý lỗi tự nhiên
  • Variadic functions accept zero or more arguments using ... syntaxHàm variadic chấp nhận không hoặc nhiều đối số bằng cú pháp ...
  • Go functions are first-class values that can be assigned and passed aroundHàm Go là giá trị hạng nhất có thể được gán và truyền
  • Closures capture variables from their enclosing scope and maintain stateClosure bắt giữ biến từ phạm vi bao quanh và duy trì trạng thái

Practice

Test your understanding of this chapter

Quiz

How do you declare a function in Go that returns multiple values?

Bạn khai báo hàm Go trả về nhiều giá trị như thế nào?

Quiz

What does the ... operator do in the context func sum(nums ...int)?

Toán tử ... làm gì trong ngữ cảnh func sum(nums ...int)?

True or False

In Go, you can have multiple init() functions in the same package, and they all execute before main().

Trong Go, bạn có thể có nhiều hàm init() trong cùng một gói, và tất cả chúng đều thực thi trước main().

True or False

When you pass a slice to a variadic function using ..., the elements are unpacked and passed as separate arguments.

Khi bạn truyền một slice cho hàm variadic bằng ..., các phần tử được giải nén và truyền dưới dạng các đối số riêng biệt.

Code Challenge

Complete the closure to capture a multiplier

Hoàn thành closure để bắt giữ một thừa số

func makeMultiplier(factor int)  {
    return func(x int) int {
        return x * factor
    }
}
Built: 6/25/2026, 3:03:36 PM