Static local variable in Go

前端 未结 3 834
星月不相逢
星月不相逢 2021-02-11 16:35

Is it possible to define a local variable in Go that can maintain its value from one function call to another? In C, we can do this using the reserved word static.<

3条回答
  •  太阳男子
    2021-02-11 17:02

    You can do something like this

    package main
    
    import (
        "fmt"
    )
    
    func main() {
      f := do()
      f() // 1
      f() // 2
    }
    
    func do() (f func()){
      var i int
      f = func(){
        i++
        fmt.Println(i)
      }
      return
    }
    

    Link on Playground https://play.golang.org/p/D9mv9_qKmN

提交回复
热议问题