</>
Skip to content
Go lessons (15/34)

Go — Functions

Basic functions

package main

import "fmt"

func greet(name string) string {
    return "Hello, " + name + "!"
}

func add(a, b int) int {
    return a + b
}

func main() {
    fmt.Println(greet("Alice"))
    fmt.Println(add(3, 4))
}

Multiple return values

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("division by zero")
    }
    return a / b, nil
}

func swap(a, b int) (int, int) {
    return b, a
}

func main() {
    result, err := divide(10, 3)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Result:", result)

    x, y := swap(1, 2)
    fmt.Println(x, y)
}

Named return values

func divide(a, b float64) (result float64, err error) {
    if b == 0 {
        err = fmt.Errorf("division by zero")
        return
    }
    result = a / b
    return
}

Variadic functions

func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

func main() {
    fmt.Println(sum(1, 2, 3))       // 6
    fmt.Println(sum(1, 2, 3, 4, 5)) // 15

    nums := []int{1, 2, 3}
    fmt.Println(sum(nums...)) // Unpack slice
}

Function types

type MathOp func(int, int) int

func add(a, b int) int { return a + b }
func mul(a, b int) int { return a * b }

func apply(op MathOp, a, b int) int {
    return op(a, b)
}

func main() {
    fmt.Println(apply(add, 3, 4)) // 7
    fmt.Println(apply(mul, 3, 4)) // 12
}

Closures

func counter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    inc := counter()
    fmt.Println(inc()) // 1
    fmt.Println(inc()) // 2
    fmt.Println(inc()) // 3
}

Methods

type Rectangle struct {
    Width, Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

func (r *Rectangle) Scale(factor float64) {
    r.Width *= factor
    r.Height *= factor
}

func main() {
    r := Rectangle{Width: 5, Height: 3}
    fmt.Println("Area:", r.Area())
    r.Scale(2)
    fmt.Println("Scaled area:", r.Area())
}

Defer

func readFile(filename string) error {
    file, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer file.Close() // Runs when function returns

    // Process file...
    return nil
}

Panic and recover

func risky() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered:", r)
        }
    }()
    panic("something went wrong")
}

func main() {
    risky() // Prints: Recovered: something went wrong
}

Mini Practice

Write Go code that:

  1. Creates a function with multiple return values
  2. Uses a variadic function
  3. Creates a closure that maintains state
  4. Uses defer for cleanup

Up Next

In the next lesson, you'll learn about Arrays — fixed-size collections.

Related Topics

Frequently Asked Questions about Functions

What is Functions in Go?

Functions is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Functions?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Functions.

Why is Functions important in Go?

Functions is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.