Skip to main content
Go Language Fundamentals for Beginners to Advanced
CHAPTER 09 Beginner

Functions in Go

Updated: May 17, 2026
5 min read

# CHAPTER 9

Functions in Go

1. Introduction

If you write all your code inside main(), your program will quickly become an unreadable, 5,000-line mess. Functions allow you to break your code into small, reusable, and testable blocks. A function takes inputs, performs a specific task, and returns outputs.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Declare and call basic functions.
  • Pass parameters into functions.
  • Return values from functions.
  • Utilize Go's unique feature: Multiple Return Values.
  • Understand Variadic functions.

3. Declaring and Calling a Function

You define a function using the func keyword, followed by the function name, parentheses (), and curly braces {}.
go
12345678910111213
package main
import "fmt"

// 1. Function Declaration
func sayHello() {
    fmt.Println("Hello from a custom function!")
}

func main() {
    // 2. Calling the Function
    sayHello()
    sayHello() // Reusability!
}

4. Parameters and Arguments

You can pass data *into* a function. The variables in the definition are called Parameters. The actual data you pass in is called the Argument.
go
123456789
// Takes a string parameter named 'user'
func greetUser(user string) {
    fmt.Printf("Welcome, %s!\n", user)
}

func main() {
    greetUser("Alice") // "Alice" is the argument
    greetUser("Bob")
}

Syntax Shortcut: If multiple parameters share the same type, you only need to write the type once at the end!

go
1234
// Instead of (a int, b int)
func add(a, b int) {
    fmt.Println("Sum:", a + b)
}

5. Return Values

A function can perform a calculation and hand the result *back* to the code that called it using the return keyword. You must specify the return data type in the function signature.
go
123456789
// Returns an integer
func multiply(x, y int) int {
    return x * y
}

func main() {
    result := multiply(5, 4)
    fmt.Println("Result is:", result) // Prints 20
}

6. Multiple Return Values (Go's Superpower)

In C++ or Java, a function can only return ONE thing. If you want to return two things, you have to create a complex object or array.

Go allows functions to return multiple values natively! This is heavily used in Go for Error Handling (returning the result AND an error status).

go
123456789101112
// Returns two integers
func getMinMax(a, b int) (int, int) {
    if a > b {
        return b, a
    }
    return a, b
}

func main() {
    min, max := getMinMax(100, 5)
    fmt.Printf("Min: %d, Max: %d\n", min, max)
}

7. The Blank Identifier _

What if a function returns two values, but you only care about the first one? Go throws a compiler error if you declare a variable and don't use it. To ignore a return value, use the Blank Identifier (_).
go
12
min, _ := getMinMax(100, 5) // Ignores the max value entirely!
fmt.Println("Only care about min:", min)

8. Named Return Values

You can name your return variables directly in the function signature. Go will automatically declare them, and a bare return will send them back.
go
12345
func calculateRectangle(length, width int) (area int, perimeter int) {
    area = length * width
    perimeter = 2 * (length + width)
    return // "Naked return" - automatically returns area and perimeter
}

*Note: Use naked returns sparingly, as they can hurt readability in long functions.*

9. Variadic Functions

Sometimes you don't know how many arguments will be passed. A variadic function accepts any number of arguments using ....
go
1234567891011121314
// Accepts any number of integers
func sumAll(numbers ...int) int {
    total := 0
    // numbers is treated as a Slice (Array)
    for _, num := range numbers {
        total += num
    }
    return total
}

func main() {
    fmt.Println(sumAll(1, 2, 3))       // 6
    fmt.Println(sumAll(10, 20, 30, 40)) // 100
}

*(Fun Fact: fmt.Println is a variadic function, which is why you can pass it infinite arguments separated by commas!)*

10. Common Mistakes

  • Forgetting to return: If your function signature promises an int (func getAge() int), you MUST have a return statement that yields an integer.
  • Scope Issues: A variable declared inside func A() cannot be seen or used by func B(). This is called Local Scope.

11. Best Practices

  • Single Responsibility Principle: A function should do exactly ONE thing. If it validates a user, saves to the database, and sends an email, break it down into three separate functions.
  • Keep functions small: If a function is over 50 lines long, consider refactoring it.

12. Exercises

  1. 1. Write a function called divide that takes two float64 numbers.
  1. 2. Have it return the division result. If the second number is 0, return 0 (we will handle proper errors later). Test it in main.

13. MCQs with Answers & Explanations

Question 1

What keyword is used to define a function in Go?

Question 2

Variables defined inside the function signature parentheses are called:

Question 3

Actual values passed to a function during a call are called:

Q4. Can a Go function return multiple values at the same time? a) Yes b) No Answer: a) Yes. *Explanation: This is a core feature of Go, heavily used for error handling.*
Question 5

How do you specify that a function returns two integers?

Question 6

What does the blank identifier (_) do?

Question 7

What does numbers ...int mean in a function signature?

Question 8

What happens if a function promises to return an int but lacks a return statement?

Question 9

If you have parameters (x int, y int), what is the syntax shortcut?

Question 10

What is a "naked return"?

14. Interview Preparation

Interview Questions:
  1. 1. Why does Go support multiple return values, and what is its most common use case? (Answer: Returning the actual result AND an error status simultaneously).
  1. 2. Explain what the blank identifier _ is used for in function returns.

15. Summary

Functions modularize code, making it readable and reusable. They accept inputs (Parameters) and produce outputs (Returns). Go uniquely enhances functions by allowing Multiple Return Values, which completely changes how we handle data flow and errors compared to older languages.

16. Next Chapter Recommendation

Now we know how to pass a single variable into a function. But what if we need to pass 1,000 users? In Chapter 10: Arrays and Slices, we will learn how to group large amounts of data into a single collection.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·