


How do I pass a function literal as an argument to another function in Go?
Jun 22, 2025 pm 03:33 PMIn Go, it can be used by passing the function literal as a parameter to other functions, provided that its signature matches the expected parameter type of the received function. 1. The function is the first citizen in Go and can be passed as a parameter; 2. When passing, it is necessary to ensure that the types of parameters and return values ??are exactly the same as the requirements of the received function; 3. Anonymous functions can be defined and passed directly in the function call, suitable for short callbacks or one-time logical blocks; 4. The function literals can also be assigned to the variable first to improve readability or reusability; 5. Common use cases include callbacks in HTTP handlers, custom sorting, library configuration options, and logical encapsulation within higher-order functions.
In Go, you can pass a function literal (also known as an anonymous function) directly as an argument to another function, provided the signature of the function literal matches the expected parameter type. Here's how to do it effectively.
Understanding Function Types in Go
Before passing a function literal, it's important to understand that functions in Go are first-class citizens — they can be assigned to variables, passed as arguments, and even returned from other functions.
When you're passing a function literal as an argument, you need to make sure its signature (input and output types) matches what the receiving function expects.
For example:
func process(fn func(int) int) { fmt.Println(fn(5)) }
Here, process
expects a function that takes an int
and returns an int
.
So this would work:
process(func(x int) int { return x * 2 })
This is valid because the anonymous function matches the required signature.
Passing Anonymous Functions Inline
You can define and pass the function literal directly inside the function call. This is especially useful for short callbacks or one-off logic blocks.
A common use case might look like:
doOperation(func(a, b int) int { return ab })
Where doOperation
is defined as:
func doOperation(op func(int, int) int) { result := op(3, 4) fmt.Println(result) }
This keeps your code concise when the function logic is simple and only used once.
Make sure:
- The number and types of parameters match exactly.
- Return types also match what the function expects.
- You don't accidentally miss a signature detail, which will cause a compile-time error.
Assigning Function Literals to Variables First
Sometimes, you might want to assign the function literal to a variable before passing it. This can improve readability if the function body is longer or if you plan to reuse it elsewhere.
Example:
multiply := func(x, y int) int { return x * y } result := calculate(multiply)
Assuming calculate
has a matching signature like:
func calculate(fn func(int, int) int) int { return fn(6, 7) }
This approach gives you more flexibility and reusability without repeating the same logic.
Practical Use Cases
Function literals are commonly used in Go for:
- Callbacks in HTTP handlers
- Custom sorting with
sort.Slice
- Configuration options in libraries
- Encapsulating logic within higher-order functions
For instance, using sort.Slice
:
names := []string{"banana", "apple", "cherry"} sort.Slice(names, func(i, j int) bool { return len(names[i]) < len(names[j]) })
Here, we're passing a function literal to control how the slice is sorted — no need to define a separate named function.
That's the basic idea. It's not complicated, but it does require attention to function signatures.
The above is the detailed content of How do I pass a function literal as an argument to another function in Go?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In Go language, calling a structure method requires first defining the structure and the method that binds the receiver, and accessing it using a point number. After defining the structure Rectangle, the method can be declared through the value receiver or the pointer receiver; 1. Use the value receiver such as func(rRectangle)Area()int and directly call it through rect.Area(); 2. If you need to modify the structure, use the pointer receiver such as func(r*Rectangle)SetWidth(...), and Go will automatically handle the conversion of pointers and values; 3. When embedding the structure, the method of embedded structure will be improved, and it can be called directly through the outer structure; 4. Go does not need to force use getter/setter,

Go's time package provides functions for processing time and duration, including obtaining the current time, formatting date, calculating time difference, processing time zone, scheduling and sleeping operations. To get the current time, use time.Now() to get the Time structure, and you can extract specific time information through Year(), Month(), Day() and other methods; use Format("2006-01-0215:04:05") to format the time string; when calculating the time difference, use Sub() or Since() to obtain the Duration object, and then convert it into the corresponding unit through Seconds(), Minutes(), and Hours();

InGo,ifstatementsexecutecodebasedonconditions.1.Basicstructurerunsablockifaconditionistrue,e.g.,ifx>10{...}.2.Elseclausehandlesfalseconditions,e.g.,else{...}.3.Elseifchainsmultipleconditions,e.g.,elseifx==10{...}.4.Variableinitializationinsideif,l

Use bit operators to operate specific bits of integers in Go language, suitable for processing flag bits, underlying data, or optimization operations. 1. Use & (bit-wise) to check whether a specific bit is set; 2. Use

The standard way to protect critical areas in Go is to use the Lock() and Unlock() methods of sync.Mutex. 1. Declare a mutex and use it with the data to be protected; 2. Call Lock() before entering the critical area to ensure that only one goroutine can access the shared resources; 3. Use deferUnlock() to ensure that the lock is always released to avoid deadlocks; 4. Try to shorten operations in the critical area to improve performance; 5. For scenarios where more reads and less writes, sync.RWMutex should be used, read operations through RLock()/RUnlock(), and write operations through Lock()/Unlock() to improve concurrency efficiency.

Using time.NewTicker in Go can implement a time-execution function. First, create a ticker and listen to its channel, and execute the objective function when a signal is received; second, the ticker should be placed in the goroutine to avoid blocking the main thread; finally, the select and interrupt signals can be combined with elegant exit. The sample code triggers the doSomething function by listening to ticker.C for loop, and ensures resource release through deferticker.Stop(); to avoid blocking the main program, put the ticker into the startTicker function and run in the goroutine; in addition, you can also use select to listen for interrupt signals to implement the program.

Yes, multiple Go versions can be installed on the same machine. It can be easily implemented using version management tools such as gvm or goenv. Gvm supports package collections, which are suitable for cross-environment testing, while goenv is similar to rbenv and is easy to operate. After installation, version switching is performed through commands such as gvmininstallgo1.20 and gvmusego1.20, and the default version is set. If you do not use the tools, you can manually install different versions to separate directories and switch by modifying the PATH environment variables, such as configuring the shell alias go120 and go121 to quickly switch. Regardless of the method, you should confirm the current version through government and check the Go binary path in the IDE to

In Go language, fmt.Println() and fmt.Printf() are two common functions for printing text to the console. 1.fmt.Println() is suitable for fast and simple output, automatically adding spaces and line breaks, suitable for basic logs or debugging; 2.fmt.Printf() provides complete formatting control, insert variables through format verbs such as %s, %d, %.2f, etc. and format the output accurately, suitable for scenarios where format specifications are required. Choose to use both according to your needs.
