Golang anonymous function and closure principle analysis

WBOY
Release: 2024-05-03 10:12:02
Original
506 people have browsed it

Yes, anonymous functions in Go can be used to quickly define one-time functions or functions that are executed immediately, while closures are used to block local variables in the anonymous function so that these variables can be accessed even if the latter returns.

Golang anonymous function and closure principle analysis

Understanding anonymous functions and closures in Go

Anonymous functions are functions that are defined directly without defining a function name. They are often used to define one-time functions, or functions that need to be executed immediately. Syntax:

func() {
  // 函数体
}
Copy after login

Closure is a technique that "locks" local variables in an anonymous function so that local variables can be accessed even after the anonymous function returns. This can be achieved by using an anonymous function as the return value of another function or method. Syntax:

func makeCounter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}
Copy after login

Practical case: Generate random numbers

The following code uses anonymous functions and closures to generate a function that generates random numbers:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    // 创建一个匿名函数,生成一个随机数
    randomFunc := func() int {
        rand.Seed(time.Now().UnixNano())
        return rand.Intn(100)
    }

    // 将匿名函数包装在一个闭包中,封锁随机数生成器
    getRand := func(r func() int) func() int {
        return func() int {
            return r()
        }
    }(randomFunc)

    // 生成 10 个随机数并打印
    for i := 0; i < 10; i++ {
        fmt.Println(getRand())
    }
}
Copy after login

Output:

32
78
15
64
12
99
17
42
5
37
Copy after login

The above is the detailed content of Golang anonymous function and closure principle analysis. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!