dongyan1808 2015-09-17 10:52
浏览 63
已采纳

未定义的err变量

As a Go "newb" I'm not sure why I'm receiving the errors undefined err and undefinded user in the console when compiling the program.

I have:

if req.Id == nil {
    user, err := signup(C, c, &req)
} else {
    user, err := update(C, c, &req)
}

if err != nil {
    c.JSON(http.StatusOK, err)
    return
}

doSomethingWith(user)

I realise I could probably declare the err and user variables before the conditional block but I would like to know why this doesn't work. Is it something to do with creating two new variables in one go?

UDPATE Getting in a bit of a mess with this.

I've now got:

user := core.User{}
if req.Id == nil {
    user, err := signup(C, c, &req)
} else {
    user, err := update(C, c, &req)
}

cleanUser(&user)

and my errors now are user declared and not used. I'm not tackling the err part at the moment but I'm unsure why I'm getting errors about the user.

  • 写回答

1条回答 默认 最新

  • dongyihao1099 2015-09-17 10:55
    关注

    It's because the scope of the err variable you're creating: it is only in scope (and therefore valid/referable) till the end of innermost block in which you declared it.

    Spec: Declarations and scope

    The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.

    When you declare it before the if statement, then it will be in scope till the end of the container block which also includes the 2nd if where you test the err variable, so that is ok.

    UDPATE:

    Update to your update: you used a Short variable declaration which creates new variables because you used it in a new block. You haven't used these new variables (only the "other" user declared outside the inner block) hence the compile time error "user declared and not used".

    Solution is simple: simply declare both variables before the if and don't use short variable declaration but simply assignment:

    user := core.User{}
    var err error
    
    if req.Id == nil {
        user, err = signup(C, c, &req)
    } else {
        user, err = update(C, c, &req)
    }
    
    if err == nil {
        cleanUser(&user)
    }
    

    Or using one line to declare both user and err:

    user, err := core.User{}, error(nil)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?