Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shockalotti/6cbfc0aee8825bad168a to your computer and use it in GitHub Desktop.
Save shockalotti/6cbfc0aee8825bad168a to your computer and use it in GitHub Desktop.
Go Golang - pointers exercise, swap x and y
package main
import "fmt"
func swap(px, py *int) {
tempx := *px
tempy := *py
*px = tempy
*py = tempx
}
func main() {
x := int(1)
y := int(2)
fmt.Println("x was", x)
fmt.Println("y was", y)
swap(&x, &y)
fmt.Println("x is now", x)
fmt.Println("y is now", y)
}
@dineshsonachalam
Copy link

dineshsonachalam commented May 24, 2020

Approach 1: Using a temporary(temp) variable to store the value of x

package main
import "fmt"

func swap(x *int, y *int) {
	temp := *x
	*x = *y
	*y = temp
}

func main(){
	x,y := 5,10
	fmt.Println("Before SWAP: ",x,y)
	swap(&x,&y)
	fmt.Println("After SWAP:  ",x, y)
}

/*
Output:
Before SWAP:  5 10
After SWAP:   10 5
*/

Approach 2: No mediators used

package main
import "fmt"

func swap(x *int, y *int) {
	*x,*y = *y,*x
}

func main(){
	x,y := 5,10
	fmt.Println("Before SWAP: ",x,y)
	swap(&x,&y)
	fmt.Println("After SWAP:  ",x, y)
}

/*
Output:
Before SWAP:  5 10
After SWAP:   10 5
*/

@PureSoulShard
Copy link

Ty, bro for your useful code.
+1 STAR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment