gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:27:18 26 4
gpt4 key购买 nike

这段代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com