A simple 'Go' program to swap variable values with pointers
Code:
// this statement is required on all programs that should compile as an executable
package main
//to import the 'fmt' package that implements formatted I/O functions
import "fmt"
// * is used to indicate pointers
// * is also used to indicate the value inside the pointers
func swap(xPtr *int, yPtr *int) {
//Println means Print line
fmt.Println("The value in location", xPtr, "is", *xPtr)
fmt.Println("The value in location", yPtr, "is", *yPtr)
fmt.Println("The values are being swapped")
*xPtr, *yPtr = *yPtr, *xPtr
}
func main() {
// := is used when the variable is initialized
x := 1
y := 2
fmt.Println("The location in memory for variable x is ", &x)
fmt.Println("The location in memory for variable y is ", &y)
// & is used to refer to the location in memory
swap(&x, &y)
fmt.Println("The value in location", &x, "is", x)
fmt.Println("The value in location", &y, "is", y)
}
c:\Go\src\test>go run test.go
The location in memory for variable x is 0xc042054058
The location in memory for variable y is 0xc042054070
The value in location 0xc042054058 is 1
The value in location 0xc042054070 is 2
The values are being swapped
The value in location 0xc042054058 is 2
The value in location 0xc042054070 is 1
--end-of-post--