2016-07-25 112 views

回答

8

是的,這是可能的。假設ab具有相同的類型,所提供的示例將工作得很好。例如:

a, b := "second", "first" 
fmt.Println(a, b) // Prints "second first" 
b, a = a, b 
fmt.Println(a, b) // Prints "first second" 

Run sample on the playground

這是法律和習慣,所以沒有必要使用一箇中間的緩衝區。

4

是,能夠使用元組分配到交換元素:

i := []int{1, 2, 3, 4} 
fmt.Println(i) 

i[0], i[1] = i[1], i[0] 
fmt.Println(i) 

a, b := 1, 2 
fmt.Println(a, b) 

a, b = b, a // note the lack of ':' since no new variables are being created 
fmt.Println(a, b) 

輸出:

[1 2 3 4] 
[2 1 3 4] 
1 2 
2 1 

實施例:https://play.golang.org/p/sopFxCqwM1

更多細節這裏:https://golang.org/ref/spec#Assignments