dongzhou5344 2017-09-04 19:29
浏览 5

多次返回时始终是新变量

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!

  • 写回答

2条回答 默认 最新

  • download20151010 2017-09-04 19:50
    关注

    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.

    评论

报告相同问题?