英文:
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.
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论