初始化
This commit is contained in:
3
01_basics/05_functions/03_anonymous/go.mod
Normal file
3
01_basics/05_functions/03_anonymous/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module anonymous
|
||||
|
||||
go 1.23.5
|
34
01_basics/05_functions/03_anonymous/main.go
Normal file
34
01_basics/05_functions/03_anonymous/main.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
// 立即执行的匿名函数
|
||||
func(msg string) {
|
||||
fmt.Println(msg)
|
||||
}("立即执行的匿名函数")
|
||||
|
||||
// 将匿名函数赋值给变量
|
||||
greet := func(name string) {
|
||||
fmt.Printf("Hello, %s!\n", name)
|
||||
}
|
||||
greet("Gopher")
|
||||
|
||||
// 闭包示例
|
||||
adder := func() func(int) int {
|
||||
sum := 0
|
||||
return func(x int) int {
|
||||
sum += x
|
||||
return sum
|
||||
}
|
||||
}
|
||||
|
||||
// 使用闭包
|
||||
pos, neg := adder(), adder()
|
||||
for i := 0; i < 5; i++ {
|
||||
fmt.Println(
|
||||
"pos:", pos(i),
|
||||
"neg:", neg(-2*i),
|
||||
)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user