duanpie4763 2013-06-14 13:59
浏览 50
已采纳

前往:声明一个新变量并覆盖更高范围的变量,如何?

I cannot find the answer anywhere, so this is the situation:

// err has not yet been declared here
globalVar := "string"
if globalVar == "string" {
    globalVar, err := doSomethingWithString()
    if err != nil {
        // error handling
    }
}

That second globalVar declaration gives an error both then := and when '=' is used:

  • With := it says globalVar declared and not used because now globalVar is a new variable in the inner scope.
  • With = it says undefined err because it has not yet been declared.

So basically, there should be a way to define the difference between = and := for each variable on the left side of the declaration.

I see two possible solutions, which are both equally ugly in my opinion:

// err has not yet been declared here
globalVar := "string"
if globalVar == "string" {
    globalVar2, err := doSomethingWithString()
    if err != nil {
        // error handling
    }
    globalVar = globalVar2
}

or

globalVar := "string"
var err error
if globalVar == "string" {
    globalVar, err = doSomethingWithString()
    if err != nil {
        // error handling
    }
}

Do I have to use one of these work-arounds or is there a correct way of achieving what I need?

The second solution seems the least ugly, but if there are many variables you only need in the if-scope, these variables will not be removed after the scope and persist the whole outer scope. So the fist solution seems the best in my opinion.

But I'd like to hear how others resolve this situation...

  • 写回答

1条回答 默认 最新

  • dongren1986 2013-06-14 16:10
    关注

    Just don't use := in this case and predeclare both globalVar and err.

    var (
        globalVar string
        err error
    )
    
    globalVar = "string"
    if globalVar == "string" {
        globalVar, err = doSomethingWithString()
        if err != nil {
            // error handling
        }
    }
    

    or alternatively if you want to limit the scope of err:

    globalVar := "string"
    if globalVar == "string" {
        var err error
        globalVar, err = doSomethingWithString()
        if err != nil {
            // error handling
        }
    }
    

    http://play.golang.org/p/73bF_tHYsC for an example similar to the previous answer.

    := is meant as a convenience when you want to declare and assign in one statement. If it's getting in the way just don't use it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Windows Script Host 无法找到脚本文件"C:\ProgramData\Player800\Cotrl.vbs”
  • ¥15 matlab自定义损失函数
  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图