英文:
Always a new variable when multiple returns
问题
我在使用Golang时遇到了一个奇怪的问题。
在init()
函数中,我想给在该函数之外声明的变量赋值。
但是为了给这个变量赋值,我需要获取一个error
来检查是否一切正常。
以下是代码:
var retryValue time.Duration
func init() {
retryValue, err := time.ParseDuration(retries)
if err != nil {
log.Fatal("retries value is invalid", err)
}
}
func a(){
fmt.Println(retryValue)
}
然后我得到了编译错误:
retryValue declared and not used
我需要将init()
函数改为以下形式:
func init() {
var err error
retryValue, err = time.ParseDuration(retries)
if err != nil {
log.Fatal("retries value is invalid", err)
}
}
还有其他解决这个问题的方法吗?
:=
操作符总是会创建一个新的变量,如果其中一个变量已经声明了吗?这与Golang的变量作用域有关吗?
谢谢!
英文:
I'm facing a wierd problem with Golang.
On init()
function, i want to assign a value to my variable that was declared outside this function.
But to assign the value to this var, i need to get
error
to check if everything is ok.
Here is the code:
var retryValue time.Duration
func init() {
retryValue, err := time.ParseDuration(retries)
if err != nil {
log.Fatal("retries value is invalid", err)
}
}
func a(){
fmt.Println(retryValue)
}
And i get the compiling error:
retryValue declared and not used
I need to change init()
to this:
func init() {
var err error
retryValue, err = time.ParseDuration(retries)
if err != nil {
log.Fatal("retries value is invalid", err)
}
}
There is another way to solve this problem?
:=
always create a new variable if one of the variables are already declared? It's about variable golang's sope?
Thanks!
答案1
得分: 2
有两种基本方法可以实现这个。你找到了其中一种:
var retryValue time.Duration
func init() {
var err error
retryValue, err = time.ParseDuration(retries)
if err != nil {
log.Fatal("retries value is invalid", err)
}
}
稍微更简短的方法是:
var retryValue = func() time.Duration {
rv, err := time.ParseDuration(retries)
if err != nil {
log.Fatal("retries value is invalid", err)
}
return rv
}()
但比这两种方法更好的是,直接指定值,而不是解析它:
var retryValue = 15 * time.Minute // 或者你想要的任何值
英文:
There are two basic ways to do this. You found one:
var retryValue time.Duration
func init() {
var err error
retryValue, err = time.ParseDuration(retries)
if err != nil {
log.Fatal("retries value is invalid", err)
}
}
A slightly shorter method would be:
var retryValue = func() time.Duration {
rv, err := time.ParseDuration(retries)
if err != nil {
log.Fatal("retries value is invalid", err)
}
return rv
}()
But better than either of these, would be to just specify the value directly, rather than parsing it:
var retryValue = 15 * time.Minute // or whatever value you want
答案2
得分: -2
你的修复确实是解决这个问题的最简单方法,而且没有其他解决方法。
这个问题很少见,实际上并不是一个实际问题,毕竟只是多了一行(短)代码。
英文:
Your fix is indeed the shortest way to do this, and no there is not another way to solve the issue.
This problem is rare enough that it is not really an issue in practice, after all it is only one more (short) line.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论