Home > Backend Development > Golang > Anonymous function for golang function

Anonymous function for golang function

王林
Release: 2024-04-20 12:27:02
Original
754 people have browsed it

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 for golang function

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() {
    // 函数体
}
Copy after login

Anonymous functions can accept parameters and return results, just like ordinary functions:

func(x int) int {
    return x * x
}
Copy after login

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)
}
Copy after login

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
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template