Advertisement
Koepnick

pointers

Jan 15th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.59 KB | None | 0 0
  1. a := 5
  2. // Store the memory address of the variable
  3. b := &a // 0xc0000140e8
  4. // Read the variable at a specific memory address
  5. c := *b // 5
  6. // Set the variable at a specific memory address
  7. *b = 10
  8. fmt.Println(a)  // 10
  9.  
  10. // Explicit definition
  11. var d = *int
  12. d = &a      // 0xc0000140e8
  13.  
  14. // So what's the point?
  15. // Unscoped functions can operate directly on a memory address
  16. // No need for globals
  17. // Consider...
  18. func pzero(xPtr *int) {
  19.     *xPtr = 0
  20. }
  21. func zero(x int) {
  22.     x = 0
  23. }
  24. func main() {
  25.     x := 5
  26.     y := 5
  27.     fmt.Println(x, y) // 5, 5
  28.     pzero(&x)
  29.     zero(y)
  30.     fmt.Println(x, y) // 0, 5
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement