如何在GO中实现静态局部变量
我和Go一起学习曲线。我喜欢:-)
好吧,我想实现这样的静态局部变量以避免声明全球。但是我在封闭中挣扎。我只想在函数首次调用时仅打印一条消息,而不是其他时间。
这是我的
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
...
}
代码中的代码本地代码如果Len(...
从未称为
避免添加全局变量的方法?
谢谢您的帮助
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
GO中没有“静态局部变量”。
如果功能需要状态,则有很多选择。在 Go Playground 。
您可以使用软件包级别变量:
测试:
或将(指针转到)作为参数:
测试:
或者您可以使用方法,并且状态可以存储在接收器中:
测试:
或使用
sync.once.once
也是并发安全:测试:
或返回a closure /em>指的是局部变量:
测试:
您也可以使用函数变量,将a closure 分配给它:
测试:
您也可以使用方法值作为函数:
测试:
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:
Testing:
Or pass the (pointer to) state as an argument:
Testing:
Or you may use a method and the state may be stored in the receiver:
Testing:
Or use
sync.Once
which is also concurrency safe:Testing:
Or return a closure that refers to a local variable:
Testing:
You may also use a function variable, assigning a closure to it:
Testing:
You may also use a method value as a function:
Testing: