Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mknparreira/45dd9a42a2175efc34372372a45074f7 to your computer and use it in GitHub Desktop.
Save mknparreira/45dd9a42a2175efc34372372a45074f7 to your computer and use it in GitHub Desktop.
Golang | Understanding pointers once and for all
package main

import (
	"fmt"
)

func main() {
	
	x := 10
	y := &x
	
	fmt.Printf("Initial value of X:\n %#v\n", x)
	fmt.Printf("Pointer of X:\n %#v\n", &x)
	fmt.Printf("Y recieves ponter of X:\n %#v\n", y)
	
	*y++
	fmt.Printf("Final value of X:\n %#v\n", x)
	fmt.Printf("Final value of Y:\n %#v\n", *y)
	
	fmt.Println("--------------------------------")
	
	z := 11
	t := z
	t++
	
	fmt.Printf("Initial value of Z:\n %#v\n", z)
	fmt.Printf("Pointer of Z:\n %#v\n", &z)
	fmt.Printf("T does not recieve pointer of Z:\n %#v\n", &t)
	fmt.Printf("Final value of Z:\n %#v\n", z)
	fmt.Printf("Final value of T:\n %#v\n", t)
}

/*
Initial value of X:
 10
Pointer of X:
 (*int)(0xc0000b6020)
Y recieves ponter of X:
 (*int)(0xc0000b6020)
Final value of X:
 11
Final value of Y:
 11
--------------------------------
Initial value of Z:
 11
Pointer of Z:
 (*int)(0xc0000b6028)
T does not recieve pointer of Z:
 (*int)(0xc0000b6030)
Final value of Z:
 11
Final value of T:
 12
*/
@mknparreira
Copy link
Author

See the code in Golang Playground: https://play.golang.org/p/F5tLegGGz3O

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