Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to swap variable values in Go?

Tags:

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
like image 399
Nicky Feller Avatar asked Jul 25 '16 15:07

Nicky Feller


1 Answers

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.

like image 85
Sam Whited Avatar answered Oct 12 '22 00:10

Sam Whited