Go language anonymous functions can be used to create one-time-use functions or parts of larger functions without declaring a function name. Its syntax is func() { // function body }, which accepts parameters and returns results. Practical examples include sorting slices (sorting by specific attributes via the sort.Slice function and anonymous functions) and filtering data (filtering odd numbers via the filter function and anonymous functions).
Anonymous function in Go language
Anonymous function is a function in Go language that does not need to declare a function name. They are often used to quickly create one-time-use functions or as part of a larger function.
Syntax
func() { // 函数体 }
Anonymous functions can accept parameters and return results, just like ordinary functions:
func(x int) int { return x * x }
Practical cases
Sort Slice
We can use anonymous functions in the sort.Slice
function to sort based on specific properties of slice elements:
package main import ( "fmt" "sort" ) type Person struct { Name string Age int } func main() { people := []Person{ {"John", 25}, {"Mary", 30}, {"Bob", 20}, } // 根据 age 排序 sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age }) fmt.Println(people) }
Filter data
We can also use anonymous functions to filter data:
package main import "fmt" func main() { nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} // 过滤奇数 oddNums := filter(nums, func(x int) bool { return x % 2 != 0 }) fmt.Println(oddNums) } func filter(arr []int, f func(int) bool) []int { result := []int{} for _, v := range arr { if f(v) { result = append(result, v) } } return result }
The above is the detailed content of Anonymous function for golang function. For more information, please follow other related articles on the PHP Chinese website!