Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Use Function Fields in Go Structs

Store a function in a Go struct, call it through the field, handle its nil zero value, and decide when to use a method instead.

Table of Contents

Declare a Go struct field with a function type, such as Format func(string) string. Assign any function with that signature and call it with value.Format("Ava"). Use a field when different instances need different behavior, such as a custom formatter or a callback.

Functions are fields in Golang Picture 1

Store and call a function

This runnable example gives each Greeter the option to supply its own formatter. The Greet method calls it when present and uses a default otherwise.

package main

import "fmt"

type Greeter struct {
    Format func(name string) string
}

func (g Greeter) Greet(name string) string {
    if g.Format == nil {
        return "Hello, " + name
    }
    return g.Format(name)
}

func main() {
    basic := Greeter{}
    friendly := Greeter{
        Format: func(name string) string {
            return "Hi, " + name + "!"
        },
    }
    fmt.Println(basic.Greet("Ava"))
    fmt.Println(friendly.Greet("Ava"))
}

Run the program with go run main.go. It prints:

Hello, Ava
Hi, Ava!

The zero value of a function field is nil. Calling a nil function panics. Either check the field before calling it, as above, or require and validate the function when you construct the value.

Choose between a function field and a method

A function field stores a value that can vary from one struct instance to another. A method has a receiver and is declared for the type. Only the method belongs to the type’s method set and can satisfy an interface method. In the example, Greet is a method and Format is a field. See the Go language specification for the rules on function types and method sets.

A struct can have multiple function fields with different signatures, such as OnStart func() and OnError func(error). Name each field after the job it performs and specify whether it is optional. Pass inputs explicitly when practical. A callback that closes over mutable variables can observe later changes to them, even if you copy the struct.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.