Best way to swap variable values in Go?

此生再无相见时 提交于 2020-08-22 09:37:07

问题


Is it possible to swap elements like in python?

a,b = b,a

or do we have to use:

temp = a
a = b
b = temp

回答1:


Yes, it is possible. Assuming a and b have the same type, the example provided will work just fine. For example:

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

This is both legal and idiomatic, so there's no need to use an intermediary buffer.




回答2:


Yes it is possible to swap elements using tuple assignments:

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)

Output:

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

Example: https://play.golang.org/p/sopFxCqwM1

More details here: https://golang.org/ref/spec#Assignments




回答3:


There is a function called Swapper which takes a slice and returns a swap function. This swap function takes 2 indexes and swap the index values in the slice.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    s := []int{1, 2, 3}

    fmt.Printf("Before swap: %v\n", s)

    swapF := reflect.Swapper(s)

    swapF(0, 1)

    fmt.Printf("After swap: %v\n", s)
}

Try it

Output

Before swap: [1 2 3]
After swap: [2 1 3]

Yes, you can swap values like python.

a, b := 0, 1
fmt.Printf("Before swap a = %v, b = %v\n", a, b)

b, a = a, b
fmt.Printf("After swap a = %v, b = %v\n", a, b)

Output

Before swap a = 0, b = 1
After swap a = 1, b = 0


来源:https://stackoverflow.com/questions/38571354/best-way-to-swap-variable-values-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!