[GoLang] 短变量声明

Short variable declarations
A short variable declaration uses the syntax:

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

"var" IdentifierList = ExpressionList .
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 coordinate
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.

官方说明如上,在这里要强调的是,如果父作用域中存在同名变量,那到底是重声明变量(即对父作用域变量赋值)还是一个声明了一个全新的变量呢?

从如下这个例子中可以得到答案:

var gIndex int

func init() {
	gIndex = 0
}

func dumyFunc() (string, error) {
	gIndex = gIndex + 1
	return fmt.Sprintf("string %d", gIndex), nil
}

func main() {
	var str string
	str = "string1"
	str, err := dumyFunc()
	fmt.Printf("%s %v\n", str, err)
	{
		str, err := dumyFunc()
		fmt.Printf("%s %v\n", str, err)
	}
	fmt.Printf("%s\n", str)
}

输出为:

string 1 <nil>
string 2 <nil>
string 1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值