2016-07-25 29 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