Pointers in Go

Introduction

Go supports pointers that are somewhat cut down compared with those in C and C++ pointers. Pointer arithmetic is not supported

Before reading this article it is advisable to read:

Declaring a pointer

Example

package main import ( "fmt" "reflect" ) func main() { var siteName *string = new(string) *siteName = "HeiHei" fmt.Println(siteName) fmt.Println(*siteName) fmt.Println(reflect.TypeOf(siteName)) }

go run main.go

0x340d22a4c070
HeiHei
*string

Point to a variable

Example

package main import ( "fmt" "reflect" ) func main() { siteName := "HeiHei" fmt.Println(siteName) ptr := &siteName fmt.Println(ptr, *ptr, reflect.TypeOf(ptr)) siteName = "TopBicycle" fmt.Println(ptr, *ptr, reflect.TypeOf(ptr)) }

go run main.go

HeiHei
0x23b4e92ac020 HeiHei *string
0x23b4e92ac020 TopBicycle *string

The value stored in the variable that the pointer points to has changed, but the memory address it points to has not.

Article author: Andrei Olegovich