Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save shockalotti/6cbfc0aee8825bad168a to your computer and use it in GitHub Desktop.

Select an option

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)
}
@navygg

navygg commented Sep 18, 2016

Copy link
Copy Markdown

temp := *px
*px = *py
*py = temp

or
*px, *py = *py, *px

@emirhangl

Copy link
Copy Markdown

@navygg can you tell us the difference between those two usage of assignment ?
"temp := *px
*px = *py
*py = temp

or
*px, *py = *py, *px"

@foo0x29a

Copy link
Copy Markdown

@emirhangl The difference is that in the first approach the temp variable is used to store the value of px, and then substitute by the value of py. In the second approach, no intermediary was used.

@yathatguy

Copy link
Copy Markdown

do you know how to write test for this swap function?

@yathatguy

Copy link
Copy Markdown

hm, i've got it

package main

import (
	"testing"
)

type testpair struct {
	pairs []int
	result []int
}

func TestSwap (t *testing.T)  {
	tests := []testpair{
		{[]int{1,2}, []int{2,1}},
		{[]int{5,-1}, []int{-1,5}},
		{[]int{123,-123}, []int{-123,123}},
		{[]int{0,53535}, []int{53535,0}},
	}
	for _, tc := range tests {
		swap(&tc.pairs[0], &tc.pairs[1])
		if tc.pairs[0] != tc.result[0] || tc.pairs[1] != tc.result[1] {
			t.Error(
				"Expected",
				tc.result[0],
				tc.result[1],
				"but got",
				tc.pairs[0],
				tc.pairs[1],
				)
		}
	}
}

@dineshsonachalam

dineshsonachalam commented May 24, 2020

Copy link
Copy Markdown

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
Copy Markdown

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