go-examples/swap/main.go
2017-07-07 14:29:36 +02:00

50 lines
666 B
Go

package main
import "fmt"
func swap(x, y *int) {
*x, *y = *y, *x
/*
tmp := *x
*x = *y
*y = tmp
*/
}
func rotate(ptrs ...*int) {
if len(ptrs) == 0 {
return
}
tmp := *ptrs[0]
for i := 1; i < len(ptrs); i++ {
*ptrs[i-1] = *ptrs[i]
}
*ptrs[len(ptrs)-1] = tmp
}
func main() {
x := 1
y := 2
swap(&x, &y)
fmt.Println("x =", x)
fmt.Println("y =", y)
a := 1
b := 2
c := 3
rotate(&a, &b, &c)
fmt.Println("a =", a)
fmt.Println("b =", b)
fmt.Println("c =", c)
rotate(&a, &b, &c)
fmt.Println("a =", a)
fmt.Println("b =", b)
fmt.Println("c =", c)
rotate(&a, &b, &c)
fmt.Println("a =", a)
fmt.Println("b =", b)
fmt.Println("c =", c)
}