'How to implement static local variable in go [duplicate]
I'm in the learning curve with go. I like like :-)
Well, I would like to implement such a static local variable to avoid to declare a global one. But I struggle with closure. I would like to print a message only the first time the function is called, and not the other times.
Here is my code
func append(path string, vars Vars) {
// raise a warning only once
func() (func()){
var f bool
return func(){
if len(vars["hostlurl"]) == 0 && !f {
f = true
fmt.Println("Warning: missing hosturl.")
}
}
}()
// append
...
}
In this code the local code if len(... is never called
Is there a way to avoid to add a global variable?
Thank you for your help
Solution 1:[1]
There are no "static local variables" in Go.
If a function needs a state, you have numerous options. Try all on the Go Playground.
You may use a package level variable:
var state bool
func f1() {
if !state {
state = true
fmt.Println("f1() first")
}
fmt.Println("f1() called")
}
Testing:
f1()
f1()
// Output
f1() first
f1() called
f1() called
Or pass the (pointer to) state as an argument:
func f2(state *bool) {
if !*state {
*state = true
fmt.Println("f2() first")
}
fmt.Println("f2() called")
}
Testing:
var state bool
f2(&state)
f2(&state)
// Output
f2() first
f2() called
f2() called
Or you may use a method and the state may be stored in the receiver:
type foo struct {
state bool
}
func (v *foo) f3() {
if !v.state {
v.state = true
fmt.Println("foo.f3() first")
}
fmt.Println("foo.f3() called")
}
Testing:
v := foo{}
v.f3()
v.f3()
// Output
foo.f3() first
foo.f3() called
foo.f3() called
Or use sync.Once which is also concurrency safe:
var f2Once sync.Once
func f4() {
f2Once.Do(func() {
fmt.Println("f4() first")
})
fmt.Println("f4() called")
}
Testing:
f4()
f4()
// Output
f4() first
f4() called
f4() called
Or return a closure that refers to a local variable:
func f5() func() {
var state bool
return func() {
if !state {
state = true
fmt.Println("f5() first")
}
fmt.Println("f5() called")
}
}
Testing:
fret := f5()
fret()
fret()
// Output
f5() first
f5() called
f5() called
You may also use a function variable, assigning a closure to it:
var f6 = func() func() {
var state bool
return func() {
if !state {
state = true
fmt.Println("f6() first")
}
fmt.Println("f6() called")
}
}()
Testing:
f6()
f6()
// Output
f6() first
f6() called
f6() called
You may also use a method value as a function:
type bar struct {
state bool
}
func (v *bar) f7() {
if !v.state {
v.state = true
fmt.Println("foo.f7() first")
}
fmt.Println("foo.f7() called")
}
var f7 = (&bar{}).f7
Testing:
f7()
f7()
// Output
f7() first
f7() called
f7() called
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
