A 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, 10f := 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
概括:短變量聲明只需要指定變量標(biāo)識(shí)符以及對(duì)應(yīng)的值列表,編譯器會(huì)根據(jù)值的類型自動(dòng)推導(dǎo)出變量的類型。
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.
不同于常規(guī)變量聲明,在相同塊中且至少有一個(gè)新的非空白變量的短變量聲明中,可對(duì)原先聲明的變量以相同的類型重聲明。因此,重聲明只能出現(xiàn)在多變量的短聲明中。 重聲明沒(méi)有生成新的變量;它僅僅賦予新的值給原來(lái)的變量。
field1, offset := nextField(str, 0)field2, offset := nextField(str, offset) // redeclares offseta, 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
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注