Skip to content

Instantly share code, notes, and snippets.

@artturijalli
Created March 20, 2021 09:47
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 artturijalli/dff63025ed9bd9230063f07c27a6d096 to your computer and use it in GitHub Desktop.
Save artturijalli/dff63025ed9bd9230063f07c27a6d096 to your computer and use it in GitHub Desktop.
An example of using pointers in Go.
package main
import "fmt"
func main() {
// POINTERS
i := 7
// The value of i
fmt.Println(i) // prints 7
// A Pointer to i's memory address
fmt.Println(&i) // prints the memory address of i, e.g. 0xc000018050
// Try to increment i using addOne (implemented below, outside the Main function)
addOne(i)
fmt.Println(i) // ...but it remains 7. This is because addOne just operates on a copy of i
addOneReally(&i) // pass in the pointer to the i's memory address
fmt.Println(i) // prints 8
}
// Increment the argument by 1
func addOne(x int){
// copy the variable passed in and operate on that
x++
}
// Increment the value behind the memory address by 1
func addOneReally(x *int){
// get the value behind the argument's memory address and increment it by 1
*x++
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment