Golang 歧义 err 重定义
Golang ambiguous err redefinition
为什么可以重新定义 err
变量?
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.")
}
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.
简短的变量声明主要用于当你必须声明临时使用的变量时,这些变量名也可以在进一步的程序中使用。例如,"err" 可以在进一步的程序中随时使用。
假设语言是 java,您将不得不为进一步的程序声明更多不同的变量名。
但在 golang 中,短变量声明在 java 脚本中作为 "let" 工作。
希望这有帮助。
我建议尽可能使用内联检查:
// 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.")
}
为什么可以重新定义 err
变量?
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.")
}
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.
简短的变量声明主要用于当你必须声明临时使用的变量时,这些变量名也可以在进一步的程序中使用。例如,"err" 可以在进一步的程序中随时使用。 假设语言是 java,您将不得不为进一步的程序声明更多不同的变量名。 但在 golang 中,短变量声明在 java 脚本中作为 "let" 工作。 希望这有帮助。
我建议尽可能使用内联检查:
// 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.")
}