Can you declare multiple variables at once in Go?

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

Can you declare multiple variables at once in Go?

问题

在Golang中,可以同时声明多个变量吗?

例如,在Python中,你可以这样写:

a = b = c = 80

所有的变量都会被赋值为80。

英文:

Is it possible to declare multiple variables at once using Golang?

For example in Python you can type this:

a = b = c = 80

and all values will be 80.

答案1

得分: 135

是的,你可以这样做:

var a, b, c string
a = "foo"
fmt.Println(a)

对于内联赋值,你可以做类似的操作,但不太方便:

a, b, c := 80, 80, 80
英文:

Yes, you can:

var a, b, c string
a = "foo"
fmt.Println(a)

You can do something sort of similar for inline assignment, but not quite as convenient:

a, b, c := 80, 80, 80

答案2

得分: 21

另一种方法是这样的:

var (
   a = 12
   b = 3
   enableFeatureA = false

   foo = "bar"
   myvar float64
   anothervar float64 = 2.4
)

对于常量也适用:

const (
  xconst    = 5
  boolconst = false
)
英文:

Another way to do this is like this

var (
   a = 12
   b = 3
   enableFeatureA = false

   foo = "bar"
   myvar float64
   anothervar float64 = 2.4
)

Also works for const

const (
  xconst    = 5
  boolconst = false
)

答案3

得分: 18

根据语言规范,这是因为变量的定义如下:

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

(来自“变量声明”)

一个类型的标识符列表,分配给一个表达式或ExpressionList。

const a, b, c = 3, 4, "foo"  // a = 3, b = 4, c = "foo",未指定类型的整数和字符串常量
const u, v float32 = 0, 3    // u = 0.0, v = 3.0
英文:

In terms of language specification, this is because the variables are defined with:

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

(From "Variable declaration")

A list of identifiers for one type, assigned to one expression or ExpressionList.

const a, b, c = 3, 4, "foo"  // a = 3, b = 4, c = "foo", untyped integer and string constants
const u, v float32 = 0, 3    // u = 0.0, v = 3.0

答案4

得分: 12

是的,你可以这样做,而且它比看起来更加微妙。

首先,你可以像这样简单地声明变量:

var a, b, x, y int  // 声明了四个类型为int的变量

你可以在函数参数声明中使用相同的语法:

func foo(a, b string) {  // 接受两个字符串参数a和b
    ...
}

然后是同时声明和赋值一个变量的简写语法。

x, y := "Hello", 10   // x是一个`string`类型的实例,y是一个`int`类型

在Golang中经常遇到的一种模式是:

result, err := some_api(...)  // 声明并设置`result`和`err`
if err != nil {
    // ...
    return err
}

result1, err := some_other_api(...)   // 声明并设置`result1`,重新赋值`err`
if err != nil {
    return err
}

因此,你可以在:=运算符的左侧给已定义的变量赋值,只要被赋值的变量中至少有一个是新的。否则,它就不是良好形式。这很巧妙,因为它允许我们在多个API调用中重用相同的错误变量,而不是为每个API调用定义一个新的变量。但要注意不要意外使用以下代码:

result, err := some_api(...)  // 声明并设置`result`和`err`
if err != nil {
    // ...
    return err
}

if result1, err := some_other_api(...); err != nil {   // result1和err都是新创建的,
                                                       // 仅在此代码块的作用域中可见。
                                                       // 这个err遮蔽了外部代码块中的err
    return err
}
英文:

Yes you can and it is slightly more nuanced than it seems.

To start with, you can do something as plain as:

var a, b, x, y int  // declares four variables all of type int

You can use the same syntax in function parameter declarations:

func foo(a, b string) {  // takes two string parameters a and b
    ...
}

Then comes the short-hand syntax for declaring and assigning a variable at the same time.

x, y := "Hello", 10   // x is an instance of `string`, y is of type `int`

An oft-encountered pattern in Golang is:

result, err := some_api(...)  // declares and sets `result` and `err`
if err != nil {
    // ...
    return err
}

result1, err := some_other_api(...)   // declares and sets `result1`, reassigns `err`
if err != nil {
    return err
}

So you can assign to already-defined variables on the left side of the := operator, so long as at least one of the variables being assigned to is new. Otherwise it's not well-formed. This is nifty because it allows us to reuse the same error variable for multiple API calls, instead of having to define a new one for each API call. But guard against inadvertent use of the following:

result, err := some_api(...)  // declares and sets `result` and `err`
if err != nil {
    // ...
    return err
}

if result1, err := some_other_api(...); err != nil {   // result1, err are both created afresh, 
                                                       // visible only in the scope of this block.
                                                       // this err shadows err from outer block
    return err
}

答案5

得分: 7

有几个答案是错误的:它们忽略了提问者是否可以一次性将多个变量设置为相同的值(对双关语抱歉)。

在Go语言中,如果a、b、c是变量,似乎不能一次性设置它们,也就是说你必须逐个设置每个变量:

a, b, c := 80, 80, 80

但是如果a、b、c是常量,你可以这样做:

const (
    a = 80
    b
    c
)
英文:

Several answers are incorrect: they ignore the fact that the OP is asking whether it is possible to set several variables to the same value in one go (sorry for the pun).

In go, it seems you cannot if a, b, c are variables, ie you will have to set each variable individually:

a, b, c := 80, 80, 80

But if a, b, c are constants, you can:

const (
    a = 80
    b
    c
)

答案6

得分: 3

请尝试在go-playground中运行以下代码:

package main

import "fmt"

func main() {
    a, b := "a", "b" //声明并赋值
    var c, d string //仅声明
    fmt.Println(a, b)
    fmt.Println(c, d)
}

你可以在这个网址上进行尝试:https://play.golang.org/

英文:

Try this in the go-playground:
https://play.golang.org/

package main

import "fmt"

func main() {
	a, b := "a", "b"; //Declare And Assign
	var c, d string;  //Declare Only
	fmt.Println(a,b);
	fmt.Println(c,d);
}

答案7

得分: 3

另一种方法是使用var进行包级别的赋值

package main

import (
	"fmt"
)

var (
	a, b, c = 80, 80, 80
)

func main() {
	fmt.Println(a, b, c)
}
英文:

Another way of doing is using var for package level assignment

package main

import (
	"fmt"
)

var (
	a, b, c = 80, 80 ,80
)

func main() {
	fmt.Println(a, b, c)
}

答案8

得分: 3

长声明

var varName1, varName2 string = "value", "value"

短声明

varName1, varName2 := "value1", "value2"
英文:

long declaration

var varName1, varName2 string = "value","value"

short declaration

varName1,varName2 := "value1","value2"

huangapple
  • 本文由 发表于 2014年1月12日 13:04:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/21071507.html
匿名

发表评论

匿名网友

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

确定