Skip to content

Instantly share code, notes, and snippets.

@crazyoptimist
Created November 2, 2022 21:18
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 crazyoptimist/51920ad6eb339a858148b0de3f013938 to your computer and use it in GitHub Desktop.
Save crazyoptimist/51920ad6eb339a858148b0de3f013938 to your computer and use it in GitHub Desktop.
Pointer in Go (Checkout this gist whenever you forget the concept of pointers in Go)
package main
import "fmt"
func main() {
i, j := 42, 2701
fmt.Println(i, j)
fmt.Println(&i, &j)
// you can read "&i" as "address of i"
p := &i
// var p *int
// here, p's type is "pointer pointing to integers"
fmt.Printf("%T\n", p)
// *p
// here, * is an operator that returns what p is pointing to
// it is also called "dereferencing"
fmt.Println(*p)
// changing value of *p will change the value of i
*p = 21
fmt.Println(i)
p = &j
*p = *p / 37
fmt.Println(j)
// this function call mutates the value of i
squareVal(&i)
fmt.Println(i)
}
func squareVal(p *int) {
*p *= *p
// so, return a pointer or a value? up to ya! if you return a pointer, the Go garbage collector will have something more todo with the heap. just focus on readibility for now!!
fmt.Println(p, *p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment