Created
August 27, 2018 13:31
-
-
Save spilth/114dd54adfecebadf35168e07be0af40 to your computer and use it in GitHub Desktop.
Pointers in Go
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 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