Created
March 20, 2021 09:47
-
-
Save artturijalli/dff63025ed9bd9230063f07c27a6d096 to your computer and use it in GitHub Desktop.
An example of using 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() { | |
// 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