Last active
May 27, 2021 11:26
-
-
Save refs/28149531ef854229d1b830f7de1cd305 to your computer and use it in GitHub Desktop.
Wrapping your mind around Go's double pointer dereference
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" | |
type example struct { | |
a string | |
b string | |
} | |
// run me on https://play.golang.org/p/xxbFzUHBM6j | |
func main() { | |
// A pointer type denotes the set of all pointers to variables of a given type, called the base type of the pointer. The value of an uninitialized pointer is nil. | |
// PointerType = "*" BaseType . | |
// BaseType = Type . | |
a := &example{a: "foo", b: "bar"} | |
// fmt.Println(**a) // this results in a runtime error because a is not a pointer value. | |
b := &a | |
fmt.Printf("%T\n", b) | |
fmt.Printf("a:\t%p\nb:\t%p\n*b:\t%p\n**b:\t%v", a, b, *b, **b) // notice how *b "points" to the same memory address as a. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment