Home >Backend Development >Golang >golang function method passed as parameter
Go function methods are passed as parameters: Go functions can be passed as parameters of other functions. Code can be organized into modular and reusable pieces. Practical case: You can use the print function as a parameter to print slice elements.
Passing function methods as parameters in Go language
Function in Go is a first-class citizen, so they can be used as Pass parameters to other functions. This allows you to organize your code into modular and reusable pieces.
Syntax
func f(a int, fn func(int)) { fn(a) }
In this example, the f
function receives two parameters: an int
and a function type of func(int)
function.
Practical Case: Printing Slice Elements
Let us write a function to print slice elements that receives the print function as a parameter.
package main import "fmt" // PrintSlice 使用给定的打印函数打印切片元素 func PrintSlice(s []int, fn func(int)) { for _, v := range s { fn(v) } } func main() { numbers := []int{1, 2, 3, 4, 5} // 使用 lambda 表达式打印元素 PrintSlice(numbers, func(n int) { fmt.Println(n) }) // 使用命名函数打印元素 PrintSlice(numbers, func(x int) { fmt.Printf("%d ", x) }) }
Output:
1 2 3 4 5 1 2 3 4 5
In this example, the PrintSlice
function accepts a slice and a print function. It then loops through the slice and passes each element to the print function.
The above is the detailed content of golang function method passed as parameter. For more information, please follow other related articles on the PHP Chinese website!