Created
November 2, 2022 21:18
-
-
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)
This file contains hidden or 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() { | |
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