Created
May 29, 2014 05:27
-
-
Save shockalotti/6cbfc0aee8825bad168a to your computer and use it in GitHub Desktop.
Go Golang - pointers exercise, swap x and y
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 can you tell us the difference between those two usage of assignment ?
"temp := *px
*px = *py
*py = temp
or
*px, *py = *py, *px"
@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.
do you know how to write test for this swap function?
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],
)
}
}
}
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
*/
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
temp := *px
*px = *py
*py = temp
or
*px, *py = *py, *px