Skip to content

Instantly share code, notes, and snippets.

@spilth
Created August 27, 2018 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spilth/114dd54adfecebadf35168e07be0af40 to your computer and use it in GitHub Desktop.
Save spilth/114dd54adfecebadf35168e07be0af40 to your computer and use it in GitHub Desktop.
Pointers in Go
package main
import (
"fmt"
)
func main() {
// Create variable i that holds an integer value
var i int
// Create variable p that can hold the memory address of an integer variable
var p *int
fmt.Println("Initially:")
fmt.Printf("i: %v\n", i)
fmt.Printf("*p: %v\n", "This would generate a `runtime error: invalid memory address or nil pointer dereference`")
fmt.Printf("&i: %v\n", &i)
fmt.Printf("p: %v\n", p)
// Set the value of p to the memory address of variable i
p = &i
fmt.Println()
fmt.Println("After `p = &i`:")
fmt.Printf("i: %v\n", i)
fmt.Printf("*p: %v\n", *p)
fmt.Printf("&i: %v\n", &i)
fmt.Printf("p: %v\n", p)
// Set the value of i to the integer 42
i = 42
fmt.Println()
fmt.Println("After `i = 42`:")
fmt.Printf("i: %v\n", i)
fmt.Printf("*p: %v\n", *p)
fmt.Printf("&i: %v\n", &i)
fmt.Printf("p: %v\n", p)
// Change the value of the integer held at the memory address that p holds
*p = 142
fmt.Println()
fmt.Println("After `*p = 142`:")
fmt.Printf("i: %v\n", i)
fmt.Printf("*p: %v\n", *p)
fmt.Printf("&i: %v\n", &i)
fmt.Printf("p: %v\n", p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment