dsfg3241 2017-12-11 17:25
浏览 22
已采纳

重新声明变量以方便使用golang?

This code:

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello, playground")

    var a bool
    var b interface{}
    b = true
    if a, ok := b.(bool); !ok {
        fmt.Println("Problem!")
    }
}

Yields this error in the golang playground:

tmp/sandbox791966413/main.go:11:10: a declared and not used
tmp/sandbox791966413/main.go:14:21: a declared and not used

This is confusing because of what we read in the short variable declaration golang docs:

Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.

So, my questions:

  1. Why can't I redeclare the variable in the code snippet above?
  2. Supposing I really can't, what I'd really like to do is find a way to populate variables with the output of functions while checking the error in a more concise way. So is there any way to improve on the following form for getting a value out of an error-able function?

    var A RealType
    if newA, err := SomeFunc(); err != nil {
        return err
    } else {
        A = newA
    }   
    
  • 写回答

3条回答 默认 最新

  • doob0526 2017-12-11 18:58
    关注

    This is happening because you are using the short variable declaration in an if initialization statement, which introduces a new scope.

    Rather than this, where a is a new variable that shadows the existing one:

    if a, ok := b.(bool); !ok {
        fmt.Println("Problem!")
    }
    

    you could do this, where a is redeclared:

    a, ok := b.(bool)
    if !ok {
        fmt.Println("Problem!")
    }
    

    This works because ok is a new variable, so you can redeclare a and the passage you quoted is in effect.

    Similarly, your second code snippet could be written as:

    A, err := SomeFunc()
    if err != nil {
        return err
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办