在简短的变量声明中重新声明来自不同块的变量
如何在简短的变量声明中从不同的块中重新声明变量?
func f() (err os.Error) {
proc, err := os.StartProcess(blah blah blah)
// the new err masks the return value?
}
How can I redeclare a variable from a different block in a short variable declaration?
func f() (err os.Error) {
proc, err := os.StartProcess(blah blah blah)
// the new err masks the return value?
}
There's a long thread about this, and an issue, but I'm interested in how to work around this for the time being.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
短变量声明的 Go 规范很明确:
因此,在简短的变量声明中,您不能重新声明最初在不同块中声明的变量。
下面的示例说明了如何通过在内部块中声明局部变量 (
e
) 并将其 (e
) 分配给变量 (err2
) 在外部块中声明。输出:
这是前面的示例,重写为使用显式常规 变量声明 并命名为 函数参数而不是隐式短变量声明。变量声明始终可以显式编写为常规变量声明或命名函数参数;隐式短变量声明只是常规变量声明的简写。
输出:
在您的示例中,
err
的短变量声明重新声明了err
的返回参数声明;他们在同一个街区。因此,新的err
不会屏蔽返回参数err
。The Go specification for short variable declarations is clear:
Therefore, in a short variable declaration, you can't redeclare variables originally declared in a different block.
Here's an example of how to get around this restriction by declaring a local variable (
e
) in the inner block and assigning it (e
) to a variable (err2
) declared in an outer block.Output:
Here's the previous example rewritten to use explicit regular variable declarations and named function parameters rather than implicit short variable declarations. Variable declarations can always be written explicitly as regular variable declarations or named function parameters; implicit short variable declarations are merely a shorthand for regular variable declarations.
Output:
In your example, the short variable declaration of
err
redeclares the return parameter declaration oferr
; they are in the same block. Therefore, the newerr
does not mask the return parametererr
.无法绕过
:=
声明的范围规则。只需明确使用var
和=
即可。There is no way to bypass the scope rules of a
:=
declaration. Just be explicit usingvar
and=
.