closures _ golang

Go supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it

package main

import (
    "fmt"
)

func intSeq() func() int {
    i := 0
    return func() int {
        i += 1
        return i
    }
}

func main() {

    nextInt := intSeq()

    fmt.Println(nextInt())
    fmt.Println(nextInt())
    fmt.Println(nextInt())

    nextInts := intSeq()
    fmt.Println(nextInts())
}
1
2
3
1

总结 :

  1 : 匿名函数内部的值不是暴露在外面的....

本文来自:博客园

感谢作者:jackkiexu

查看原文:closures _ golang

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。