Skip to content

Instantly share code, notes, and snippets.

@humamfauzi
Last active August 10, 2018 13:24
Show Gist options
  • Save humamfauzi/7d81d84954e775974578a416466960bd to your computer and use it in GitHub Desktop.
Save humamfauzi/7d81d84954e775974578a416466960bd to your computer and use it in GitHub Desktop.
Note in Go Pointers
package main
import "fmt"
func main() {
var address0 *int
var number int
number = 32
address0 = &number
fmt.Println("Address ::", address0, "Value", number)
number = 72
fmt.Println("Address ::", address0, "Value", number)
address1 := &number
fmt.Println("Address ::", address0, "Value", *address1)
*address0 = 88
fmt.Println("Address ::", address0, "Value", *address1)
number = 10000
fmt.Println("Address ::", address0, "Value", *address1)
fmt.Println("ARE THEY THE SAME?", address0 == address1)
}

Pointer

This is my note of using Go pointer; how it made, how to utilize it, and what kind of common case we encounter a pointer. First note is how pointer created in Go. ✓

var mem_add *dtype

Star notation (*) used to mark a variable that it is a pointer; it only contain certain memory address. Pointer need data type (dtype). Assigning different data type to a memory address with different data type will cause an error.

address0 = &number

Ampersand notation (&) used to extract an address from a variable. In example above, we assign address0 to have memory address of variable number.

*address0 = 88

We use (*) to assign a value to a certain address.
Basic rule is . accessing memory address from a value is using ampersand line 9 . accessing value from a memory address is using star line 18

same rule is also applied when declaring

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment