Level: BeginnerGo Programs

Go Function Programs with Output: Variadic, Closures, Defer

Updated 17 min read
Go Function Programs featured image: variadic, closure and defer output

Go function programs show how to break code into small, reusable pieces, which is the first step from short scripts to real applications. In this post, you will write fourteen function programs with their exact output, covering parameters, multiple return values, variadic functions, closures, functions as values and defer. Then you will practice the function questions that interviewers ask most, with real output for each one.

This post starts Level 4 of our Go programs series. You already used small functions in our Go number programs and Go string manipulation programs. For the theory, read the Go functions guide for beginners. All programs were tested on Go 1.27.

What are Go Function Programs?

Go function programs put a piece of logic behind a name, so you can call it as many times as you need. A function takes inputs called parameters, runs its body and can return one or more results.

Think of a function as a juice machine. You put in fruit (the parameters), the machine does its work (the body), and you get juice back (the return value). You do not need to know how the machine works inside to use it again and again.

Why Go Function Programs Matter

Every Go program is built from functions, starting with main. For example, an API has a function per route, a billing system has a function for tax, and a test file has a function per test. So Go function programs teach you how to keep code short, readable and easy to test.

  • Reuse: write the logic once and call it from many places.
  • Testing: small functions are easy to test one by one.
  • Interviews: closures, variadic functions and defer order are popular questions.

How Go Function Programs Work

When you call a function, Go copies each argument into the matching parameter. The body runs with those copies. When it reaches return, the results go back to the caller, and any deferred calls run just before the function ends.

Go function programs diagram showing arguments copied into parameters, the body running and results returned
Arguments are copied into parameters, the body runs, deferred calls run at the end, and results return to the caller.

The table below lists the function features in this post.

FeatureSyntaxExample use
Parametersfunc add(a, b int) intPass values in
Multiple returnsfunc div(a, b int) (int, error)Return a result and an error
Named returnsfunc split(n int) (x, y int)Self-documenting results
Variadicfunc sum(nums …int) intAny number of arguments
Function valueop := addStore or pass a function
Closurefunc() int { count++; return count }Remember state between calls
deferdefer file.Close()Run code when the function ends

Basic Go Function Programs

These first Go function programs cover parameters and return values. If functions are new to you, start with Program 1.

Program 1: Your First Function That Says Hello

This function takes one input and prints a message. It does not return anything.

package main

import "fmt"

// greet prints a hello message for the given name.
func greet(name string) {
    fmt.Println("Hello,", name)
}

func main() {
    // Call the same function three times with different names.
    greet("Asha")
    greet("Ravi")
    greet("Meera")
}
Hello, Asha
Hello, Ravi
Hello, Meera

The line func greet(name string) creates a function with one parameter called name. Each call in main passes a different name in the brackets. Then the body runs and prints the message. You wrote the print logic once, but you used it three times.

Program 2: A Simple Function with Parameters

package main

import "fmt"

// area returns the area of a rectangle.
func area(length, width float64) float64 { // both parameters are float64, and it returns a float64
    return length * width
}

func main() {
    fmt.Println(area(12.5, 4))
    fmt.Println(area(3, 3))
}
50
9

length, width float64 means both parameters share the same type. The last float64 is the type of the result. The return line sends the answer back, and fmt.Println prints it.

Program 3: A Function That Answers Yes or No

A function can return a bool, which is either true or false. You can use the answer straight inside an if.

package main

import "fmt"

// isEven returns true when number divides by 2 with nothing left over.
func isEven(number int) bool {
    return number%2 == 0 // % gives the remainder after division
}

func main() {
    for _, number := range []int{4, 7, 10} { // range gives each index (ignored with _) and value
        if isEven(number) {
            fmt.Println(number, "is even")
        } else {
            fmt.Println(number, "is odd")
        }
    }
}
4 is even
7 is odd
10 is even

number%2 is the remainder after dividing by 2. If the remainder is 0, the comparison is true, so the number is even. The loop calls isEven for each number and picks the right message.

Program 4: Multiple Return Values

Go functions can return more than one value. This is how Go returns a result together with an error.

package main

import (
    "errors"
    "fmt"
)

// divide returns the quotient, the remainder and an error.
func divide(dividend, divisor int) (int, int, error) {
    // Step 1: stop early if the divisor is zero.
    if divisor == 0 {
        return 0, 0, errors.New("cannot divide by zero")
    }
    // Step 2: return both answers, and nil to mean "no error".
    return dividend / divisor, dividend % divisor, nil
}

func main() {
    // err holds the error value. It is nil when everything worked.
    quotient, remainder, err := divide(17, 5)
    fmt.Println(quotient, remainder, err)

    // We only need the error here, so _ throws away the other two values.
    _, _, err = divide(4, 0)
    fmt.Println(err)
}
3 2 <nil>
cannot divide by zero

This function lists three result types in brackets, so every return gives three values. The first call works, so err is nil and prints as <nil>. The blank identifier _ throws away values you do not need. Here we only care about the error in the second call.

Program 5: Named Return Values

package main

import "fmt"

// minMax returns the smallest and largest number in the slice.
func minMax(numbers []int) (smallest, largest int) {
    // Step 1: start with the first number for both.
    smallest = numbers[0]
    largest = numbers[0]
    // Step 2: check the rest. numbers[1:] means "from index 1 to the end".
    for _, number := range numbers[1:] {
        if number < smallest {
            smallest = number
        }
        if number > largest {
            largest = number
        }
    }
    return // a bare return sends back smallest and largest
}

func main() {
    smallest, largest := minMax([]int{42, 7, 19, 88, 3})
    fmt.Println(smallest, largest)
}
3 88

The results have names, smallest and largest, so they work like normal variables inside the function. Named results start at their zero values, and a bare return sends them back. Use this only in short functions, because it can hide what is being returned.

Program 6: Variadic Function

A variadic function accepts any number of arguments of one type. Inside, they arrive as a slice.

package main

import "fmt"

// total prints how many prices there are and their sum.
func total(label string, prices ...float64) { // ...float64 means "any number of float64 values"
    sum := 0.0
    for _, price := range prices { // prices is a normal slice here
        sum += price
    }
    fmt.Printf("%s: %d items, total %.2f\n", label, len(prices), sum) // %.2f shows 2 decimals
}

func main() {
    total("Cart A", 99.5, 250, 45)
    total("Cart B") // no prices at all is allowed
    cart := []float64{10, 20, 30}
    total("Cart C", cart...) // ... spreads the slice into separate arguments
}
Cart A: 3 items, total 394.50
Cart B: 0 items, total 0.00
Cart C: 3 items, total 60.00

Go collects all the extra arguments into the prices slice. With no prices, the slice is empty, so the total is 0. The variadic parameter must come last. To pass a slice you already have, add ... after it, as in cart....

Function Values in Go Function Programs

In Go function programs, functions are values. You can store them in variables, pass them to other functions and return them.

Program 7: Pass a Function as an Argument

package main

import "fmt"

// apply runs change on every number and returns the new numbers.
func apply(numbers []int, change func(int) int) []int { // change is a function that takes and returns an int
    result := make([]int, len(numbers)) // make creates a slice with room for every number
    for i, number := range numbers {
        result[i] = change(number)
    }
    return result
}

// square returns number times itself.
func square(number int) int {
    return number * number
}

func main() {
    numbers := []int{1, 2, 3, 4}
    fmt.Println(apply(numbers, square)) // pass square without () so it is not called yet

    // A function with no name, written right here, that adds 10.
    addTen := func(number int) int {
        return number + 10
    }
    fmt.Println(apply(numbers, addTen))
}
[1 4 9 16]
[11 12 13 14]

apply does not know what change it will make. It just calls whatever function you pass in. The first call passes square, and the second passes an anonymous function stored in addTen. This pattern appears all over the standard library, for example in slices.SortFunc.

Program 8: A Map of Functions for a Calculator

package main

import "fmt"

// add, subtract, multiply and divide each work on two numbers.
func add(first, second float64) float64      { return first + second }
func subtract(first, second float64) float64 { return first - second }
func multiply(first, second float64) float64 { return first * second }
func divide(first, second float64) float64   { return first / second }

func main() {
    // Each symbol (key) points to the function (value) that does the work.
    operations := map[string]func(float64, float64) float64{
        "+": add,
        "-": subtract,
        "*": multiply,
        "/": divide,
    }
    for _, symbol := range []string{"+", "-", "*", "/"} {
        operation := operations[symbol] // look up the function
        result := operation(8, 2)       // call it
        fmt.Printf("8 %s 2 = %g\n", symbol, result) // %g prints a number without extra zeros
    }
}
8 + 2 = 10
8 - 2 = 6
8 * 2 = 16
8 / 2 = 4

The map links each symbol to a function. In the loop, we look up the function by its symbol and then call it with 8 and 2. Compare this with the switch version in our Go switch programs. The map makes adding a new operator a one-line change.

Program 9: A Function That Returns a Function

package main

import "fmt"

// multiplier returns a new function that multiplies by factor.
func multiplier(factor int) func(int) int {
    return func(number int) int {
        return number * factor // the inner function remembers factor
    }
}

func main() {
    double := multiplier(2)
    triple := multiplier(3)
    fmt.Println(double(5), triple(5), double(triple(2)))
}
10 15 12

multiplier builds and returns a new function. Each returned function remembers its own factor, so double uses 2 and triple uses 3. In double(triple(2)), the inner call runs first and gives 6, then double turns it into 12.

Closures in Go Function Programs

In Go function programs, a closure is a function that remembers the variables around it, even after the outer function has finished.

Program 10: A Counter with a Closure

package main

import "fmt"

// newCounter returns a function that counts up by one on each call.
func newCounter() func() int {
    count := 0 // this variable lives on inside the returned function
    return func() int {
        count++
        return count
    }
}

func main() {
    first := newCounter()
    second := newCounter()
    fmt.Println(first(), first(), first())
    fmt.Println(second(), second())
}
1 2 3
1 2

Each call to newCounter makes a fresh count set to 0. The returned function keeps that variable and adds one on every call. first and second each have their own count. So calling first three times does not change second.

Program 11: Fibonacci Generator with a Closure

package main

import "fmt"

// fibGen returns a function that gives the next Fibonacci number on each call.
func fibGen() func() int {
    current, following := 0, 1
    return func() int {
        result := current
        // Move one step: both values change at the same time.
        current, following = following, current+following
        return result
    }
}

func main() {
    next := fibGen()
    for range 8 { // repeat 8 times (Go 1.22+)
        fmt.Print(next(), " ")
    }
    fmt.Println()
}
0 1 1 2 3 5 8 13

The closure keeps current and following between calls. Each call returns current, then moves both values one step forward. Our Go closures guide explains how Go stores these variables.

defer in Go Function Programs

defer schedules a call to run when the surrounding function returns. It is used to close files, release locks and log the end of a task.

Program 12: defer Runs in Reverse Order

package main

import "fmt"

func main() {
    fmt.Println("start")
    defer fmt.Println("first defer")  // defer waits until main is about to end
    defer fmt.Println("second defer")
    defer fmt.Println("third defer")
    fmt.Println("end")
}
start
end
third defer
second defer
first defer

The normal lines print first, in order. When main ends, the deferred calls run. They run last in, first out, like a stack of plates.

Program 13: defer Reads Arguments Early

package main

import "fmt"

func main() {
    score := 10
    defer fmt.Println("deferred score:", score) // the value 10 is saved right now
    score = 20
    fmt.Println("current score:", score)
}
current score: 20
deferred score: 10

Go evaluates the arguments of a deferred call at the moment you write defer. At that moment, score is 10. So the deferred line prints 10, not 20.

Program 14: Measure How Long a Function Takes

package main

import (
    "fmt"
    "time"
)

// timer notes the start time and returns a function that reports when the task ends.
func timer(name string) func() {
    start := time.Now()
    return func() {
        elapsed := time.Since(start) // time passed since start
        fmt.Println(name, "finished, took at least 50ms:", elapsed >= 50*time.Millisecond)
    }
}

// slowTask waits for 50 milliseconds.
func slowTask() {
    defer timer("slowTask")() // timer runs now, the returned function runs at the end
    time.Sleep(50 * time.Millisecond)
}

func main() {
    slowTask()
}
slowTask finished, took at least 50ms: true

timer("slowTask") runs at once and returns a closure. The extra () defers that closure, so it runs when slowTask ends. We print true or false instead of the exact time, so the output is the same on every run.

Value vs Pointer Parameters in Go Function Programs

In all Go function programs, Go passes a copy of each argument. The diagram and table below show what that means for values and pointers.

Go function programs comparison of value parameters and pointer parameters
A value parameter gets a copy, so changes stay inside, while a pointer parameter can change the caller’s data.
FeatureValue parameterPointer parameter
What is copiedThe whole valueOnly the address
Can change caller’s dataNoYes
Cost for big structsCopies everythingCheap
Syntaxfunc f(u User)func f(u *User)
Nil possibleNoYes, check it

So pass values for small data you only read, and pointers when the function must change the data or the data is large. We cover this fully in the pointer programs post of this level.

Common Mistakes in Go Function Programs

  • Ignoring returned errors: always check the error result instead of using _.
  • Variadic not last: a ... parameter must be the final one.
  • Forgetting … when passing a slice: total("A", cart) does not compile; use cart....
  • Expecting defer to see later changes: deferred arguments are read when defer runs.
  • Long functions: if a function needs a scroll bar, split it into smaller ones.

Best Practices for Go Function Programs

  • Keep functions short, with one clear job each.
  • Return errors as the last result, which is the Go convention.
  • Use closures for small state, such as counters, but prefer structs for bigger state.
  • Use defer for cleanup right after you open a resource.
  • Name functions with verbs, such as calculateTax or sendEmail.

Go Function Programs Interview Questions and Answers

Interviewers use short Go function programs to test rules that every developer should know. Each program is complete, with real output from Go 1.27.

Go Function Programs Parameter and Return Questions

Q1. Does Go pass arguments by value or by reference?

Always by value. Go copies each argument. A slice, map or pointer is copied too, but the copy still points to the same underlying data, which is why changes through it are visible.

Q2. What does this program print?

package main

import "fmt"

// update tries to change both of its inputs.
func update(number int, scores []int) {
    number = 100    // changes only the local copy
    scores[0] = 100 // changes the shared array behind the slice
}

func main() {
    number := 1
    scores := []int{1, 2}
    update(number, scores)
    fmt.Println(number, scores)
}
1 [100 2]

The int was copied, so the caller’s number stays 1. The slice header was copied too, but it points to the same array, so scores[0] changes.

Q3. Does Go support function overloading or default parameters?

No. Each function name must be unique in a package, and there are no default values. Use different names, a variadic parameter or an options struct instead.

Q4. What does this program print?

package main

import "fmt"

// swap returns its two inputs in the opposite order.
func swap(first, second string) (string, string) {
    return second, first
}

func main() {
    left, right := swap("left", "right")
    fmt.Println(left, right)
}
right left

Closure and Defer Questions

Q5. What does this program print?

package main

import "fmt"

func main() {
    var squareFuncs []func() int // a slice that holds functions
    for i := range 3 {
        squareFuncs = append(squareFuncs, func() int { return i * i })
    }
    for _, getSquare := range squareFuncs {
        fmt.Print(getSquare(), " ")
    }
    fmt.Println()
}
0 1 4

Since Go 1.22, each loop pass has its own i. So each closure remembers a different value.

Q6. What does this program print?

package main

import "fmt"

// calc returns 5, but a deferred function doubles it on the way out.
func calc() (result int) {
    defer func() {
        result *= 2 // runs after "return 5" has set result
    }()
    return 5
}

func main() {
    fmt.Println(calc())
}
10

return 5 sets the named result to 5, then the deferred function runs and doubles it. A deferred function can change named results, which is a classic trick question.

Q7. What does this program print?

package main

import "fmt"

func main() {
    for i := 0; i < 3; i++ {
        defer func() { fmt.Print(i, " ") }() // the () at the end calls the function (later, because of defer)
    }
    fmt.Print("loop done: ")
}
loop done: 2 1 0

Each pass has its own i, and deferred calls run in reverse order. So we see 2, 1 and 0.

Q8. What is an anonymous function?

It is a function with no name, written inline. You can call it at once, as in func() { fmt.Println("hi") }(), or store it in a variable.

package main

import "fmt"

func main() {
    // Store a function with no name in a variable.
    greet := func(name string) string {
        return "Hello, " + name
    }
    fmt.Println(greet("Meera"))

    // Write a function and call it straight away with ().
    func() {
        fmt.Println("runs immediately")
    }()
}
Hello, Meera
runs immediately

Type and Output Questions

Q9. What does this program print?

package main

import "fmt"

func main() {
    var addOne func(int) int // a function variable that is still empty (nil)
    fmt.Println(addOne == nil)
    addOne = func(number int) int {
        return number + 1
    }
    fmt.Printf("%T %d\n", addOne, addOne(1)) // %T prints the type
}
true
func(int) int 2

The zero value of a function variable is nil. Calling a nil function panics, so check it first when it might be unset.

Q10. Can you compare two functions with ==?

No. Functions can only be compared with nil. Writing f == g is a compile error.

Q11. What does this program print?

package main

import "fmt"

// sum adds up any number of whole numbers.
func sum(numbers ...int) int {
    total := 0
    for _, number := range numbers {
        total += number
    }
    return total
}

func main() {
    fmt.Println(sum(), sum(5), sum(1, 2, 3))
    fmt.Println(sum([]int{10, 20}...))
}
0 5 6
30

A variadic function can be called with zero, one or many arguments. With none, the slice is nil and the loop never runs.

Q12. What is a higher-order function?

It is a function that takes another function as an argument, or returns one. apply and multiplier in this post are both higher-order functions.

Q13. What does this program print?

package main

import "fmt"

func main() {
    count := 1
    increment := func() {
        count++ // changes the real count in main
    }
    increment()
    increment()
    fmt.Println(count)
}
3

The closure uses the real count, not a copy. So each call changes the variable in main.

Practice Task

This task reuses two Go function programs from above. Write a function makeDiscount(percent float64) func(float64) float64 that returns a function which applies the discount to a price. Create a 10% and a 25% discount and apply both to a price of 1,200. Hint: this is the same pattern as multiplier in Program 9.

Official Resources

Quick Recap

  • Go function programs take parameters, run a body and return zero or more results.
  • Go passes every argument by value, but slices, maps and pointers share their data.
  • Variadic functions take ...T as the last parameter and receive a slice.
  • Functions are values, so you can pass, store and return them.
  • Closures remember outer variables, and defer runs calls in reverse order at the end.

What’s Next?

Next, functions start calling themselves. Read Go recursion programs with output, with factorial, power, GCD and Tower of Hanoi. For the interview angle, see the Go functions interview questions.