Static local variable in Go

前端 未结 3 818
星月不相逢
星月不相逢 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

    0 讨论(0)
  • 2021-02-11 17:10

    Declare a var at global scope:

    var i = 1
    
    func a() {
      println(i)
      i++
    }
    
    0 讨论(0)
  • 2021-02-11 17:23

    Use a closure:

    Function literals are closures: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.

    It doesn't have to be in global scope, just outside the function definition.

    func main() {
    
        x := 1
    
        y := func() {
            fmt.Println("x:", x)
            x++
        }
    
        for i := 0; i < 10; i++ {
            y()
        }
    }
    

    (Sample on the Go Playground)

    0 讨论(0)
提交回复
热议问题