Golang 模糊的 err 重新定义

huangapple go评论99阅读模式
英文:

Golang ambiguous err redefinition

问题

为什么可以重新定义 err 变量?

err := ipdf.Open(source)
if err != nil {
    panic("无法打开pdf文件。")
}

payload, err := ioutil.ReadFile(other)
if err != nil {
    panic("无法读取其他文件。")
}
英文:

Why is it possible to redefine the err variable?

err := ipdf.Open(source)
if err != nil {
    panic("Couldn't open pdf.")
}

payload, err := ioutil.ReadFile(other)
if err != nil {
    panic("Couldn't read other file.")
}

答案1

得分: 8

与常规变量声明不同,短变量声明可以重新声明变量,前提是它们最初在同一代码块(或函数体的参数列表)中以相同的类型进行了声明,并且至少有一个非空变量是新的。因此,重新声明只能出现在多变量的短变量声明中。重新声明不会引入新的变量;它只是给原始变量赋予一个新值。

参考链接:https://golang.org/ref/spec#Short_variable_declarations

英文:

> 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.

https://golang.org/ref/spec#Short_variable_declarations

答案2

得分: 0

我建议尽可能使用内联检查:

// 本地作用域
if err := ipdf.Open(source); err != nil {
panic("无法打开pdf文件。")
}

payload, err := ioutil.ReadFile(other)
if err != nil {
panic("无法读取其他文件。")
}

英文:

I would recommend, as much as possible, using inline checks:

// local scope
if err := ipdf.Open(source); err != nil {
    panic("Couldn't open pdf.")
}

payload, err := ioutil.ReadFile(other)
if err != nil {
    panic("Couldn't read other file.")
}

答案3

得分: -1

短变量声明主要用于临时声明变量,并且这些变量名在后续程序中也可以使用。例如,"err" 可以在后续程序中的任何时候使用。
假设语言是 Java,你需要为后续程序声明更多不同的变量名。
但在 Go 语言中,短变量声明的工作方式类似于 JavaScript 中的 "let"。
希望这能帮到你。

英文:

Short variable declarations are used mainly when you have to declare variables for temporary use and those variable names can be used in the further program too. For example, "err" can be used anytime in the further program.
Lets assume the language was java, you would had to declare more different variable names for the further program.
But in golang, short variable declarations work as "let" in javascript.
Hope this helps.

huangapple
  • 本文由 发表于 2017年4月13日 16:57:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/43387743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定