GO Short variable declarations短变量声明

short variable declaration uses the syntax:

IdentifierList := ExpressionList


It is shorthand for a regular variable declaration with initializer expressions but no types:
var IdentifierList = ExpressionList


example:

i, j := 0, 10
f := func() int { return 7 }
ch := make(chan int)
r, w := os.Pipe(fd)  // os.Pipe() returns two values
_, y, _ := coord(p)  // coord() returns three values; only interested in y


概括:短变量声明只需要指定变量标识符以及对应的值列表,编译器会根据值的类型自动推导出变量的类型。


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.

不同于常规变量声明,在相同块中且至少有一个新的非空白变量的短变量声明中,可对原先声明的变量以相同的类型重声明。因此,重声明只能出现在多变量的短声明中。 重声明没有生成新的变量;它仅仅赋予新的值给原来的变量。


field1, offset := nextField(str, 0)
field2, offset := nextField(str, offset)  // redeclares offset
a, a := 1, 2                              // illegal: double declaration of a or no new variable if a was declared elsewhere


Short variable declarations may appear only inside functions. 
In some contexts such as the initializers for "if", "for", or "switch" statements, they can be used to declare local temporary variables

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

历史五千年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值