go - 为了方便在 golang 中重新声明一个变量?

标签 go

这段代码:

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!")
    }
}

在 golang playground 中产生这个错误:

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

这令人困惑,因为我们在简短的变量声明中读到了 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.

所以,我的问题:

  1. 为什么我不能在上面的代码片段中重新声明变量?
  2. 假设我真的做不到,我真正想做的是找到 一种用函数的输出填充变量的方法 以更简洁的方式检查错误。那么有什么办法吗 改进以下形式以从中获取值(value) 错误函数?

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

最佳答案

发生这种情况是因为您在 if 初始化语句中使用了简短的变量声明,它引入了一个新的作用域。

与此相反,a 是一个新变量,它覆盖了现有变量:

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

你可以这样做,其中 a 被重新声明:

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

这是有效的,因为 ok 是一个新变量,所以您可以重新声明 a 并且您引用的段落生效。

同样,您的第二个代码片段可以写成:

A, err := SomeFunc()
if err != nil {
    return err
}

关于go - 为了方便在 golang 中重新声明一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47758154/

相关文章:

go - 为什么 Go 中的 bool 类型是 16 字节长?

go - 在 Go 中使用 channel 对性能有好处吗?

go - 如何使用 godoc 与 go 模块一起提供文档?

arrays - 包含指向结构的指针的深度复制映射

go - 子文件夹中的深度匹配模板文件

mongodb - 无法使用Golang从MongoDB集合中获取数据

google-app-engine - Golang 谷歌存储可恢复上传 HTTP 401

json - 如何创建json数组并插入json对象

golang rabbitmq channel.consume SIGSEGV

使用 sync.WaitGroup 和 channel 的 Golang 应用程序永远不会退出