How do I declare multiple variables instantiated by a function call returning multiple values in Go?

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

How do I declare multiple variables instantiated by a function call returning multiple values in Go?

问题

假设我有一个函数:

func foo() (bool, string) { ... }

然后我希望声明两个变量 bs,并用函数调用 foo() 返回的值进行初始化。我知道可以使用省略类型注释的“简写”语法来实现:

b, s := foo();

然而,我不想使用这种简写语法。我希望使用 var 语法来声明变量名和期望的类型。我尝试了以下代码:

var b bool, s string = foo();

然而,这会导致语法错误。正确的做法是什么?

英文:

Let's say I have a function:

func foo() (bool, string) { ... }

And then I wish to declare two variables b and s, initialized with values returned by the function call foo(). I'm aware I can do this using the "shorthand" syntax which omits type annotations:

b, s := foo();

However, I do not wish to use this shorthand syntax. I wish to use the var syntax with a variable name and expected type. I have tried this:

var b bool, s string = foo();

However, this gives me a syntax error. What is the correct way to do this?

答案1

得分: 6

在大多数情况下,正确的做法是使用简写语法。这就是它的用途。

如果你不想使用简写语法,那么你可以使用var语法:

var b bool
var s string
b, s = foo()

或者

var (
	b bool
	s string
)
b, s = foo()

没有"简写var"语法。

英文:

In most cases, the correct way to do this is to use the shorthand syntax. That's what it's for.

If you don't want to use the shorthand syntax, then you can use var syntax:

var b bool
var s string
b, s = foo()

or

var (
	b bool
	s string
)
b, s = foo()

There is no "shorthand var" syntax.

答案2

得分: 2

你不能这样做。Go语言规范中定义了变量声明的语法,如下所示:

VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .

IdentifierList 中的变量只能有一个共同的 Type,或者没有 Type。你可以选择以下两种方式:

var b, s = foo()

或者,如果你想将它们放在包的顶层:

var (
    b bool
    s string
)

func init() {
    b, s = foo()
}
英文:

You can't do that. The Go Spec defines a variable declaration grammar as follows:

VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .

Variables in the IdentifierList can only have either one Type for all, or none. The best you can do is either

var b, s = foo()

or, if you want them at the top level of your package,

var (
    b bool
    s string
)

func init() {
    b, s = foo()
}

huangapple
  • 本文由 发表于 2015年3月12日 00:34:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/28992271.html
匿名

发表评论

匿名网友

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

确定