Security with Go
上QQ阅读APP看书,第一时间看更新

Pointer

Go provides a pointer type that stores the memory location where data of a specific type is stored. Pointers can be used to pass a struct to a function by reference without creating a copy. This also allows a function to modify an object in-place.

There is no pointer arithmetic allowed in Go. Pointers are considered safe because Go does not even define the addition operator on the pointer type. They can only be used to reference an existing object.

This example demonstrates basic pointer usage. It first creates an integer, and then creates a pointer to the integer. It then prints out the data type of the pointer, the address stored in the pointer, and then the value of data being pointed at:

package main

import (
"fmt"
"reflect"
)

func main() {
myInt := 42
intPointer := &myInt

fmt.Println(reflect.TypeOf(intPointer))
fmt.Println(intPointer)
fmt.Println(*intPointer)
}