7. Go language data type: pointer

Time:2020-6-9

Hi, hello.

I am Ming brother, during my time to learn Golang, I wrote detailed study notes on my personal WeChat official account “Go programming time”. For Go language, I am also a beginner, so writing things should be more suitable for students who are just in contact. If you are just learning Go language, do not pay close attention to it, learn together and grow together.

My online blog: http://golang.iswbm.com
My GitHub: github.com/iswbm/GolangCodingTime


0. What is a pointer

When we define a variable name

Var name string = "go programming time"

At this point, name is the variable name, which is just a label in the programming language for programmers to write and understand the code.

When we access this tag, the computer returns the value stored in the memory address it points to:Go programming time

For some needs, we will assign this memory address to another variable name, usually called PTR (short for pointer), which we call pointer variable.

In other words, the value of a pointer variable (a label) is a pointer, which is the memory address.

According to the value pointed to by the variable and whether it is a memory address, I divide the variable into two types:

  • Common variable: store data value itself
  • Pointer variable: memory address of memory value

1. Creation of pointer

There are three ways to create a pointer

The first method

First define the corresponding variable, then get the memory address through the variable, and create a pointer

//Define common variables
aint := 1
//Defining pointer variables
ptr := &aint

The second method

Create the pointer first, allocate the memory, and then write the corresponding value to the memory address pointed by the pointer.

//Create pointer
astr := new(string)
//Assign a value to a pointer
*ASTR = "go programming time"

The third method

First declare a pointer variable, then get the memory address from other variables and assign it

aint := 1
Var bind * int // declares a pointer
Bint = & aint // initialization

In the above three sections of code, pointer operation cannot be separated from these two symbols:

  • &: get memory address from a common variable
  • *: when*To the right of the assignment operation value is to obtain the variable value from a pointer variable, when*To the left of the assignment value is the variable to which the pointer points

With the following code, you can be familiar with the usage of these two symbols

package main

import "fmt"

func main() {
	Aint: = 1 // define common variable
	PTR: = & aint // define pointer variable
	fmt.Println ("ordinary variable stores:", aint)
	fmt.Println ("ordinary variable stores:", * PTR)
	fmt.Println (pointer variable stores:, & aint)
	fmt.Println ("pointer variable stores:", PTR)
}

The output is as follows

Common variables store: 1
Common variables store: 1
Pointer variable stores: 0xc00000100a0
Pointer variable stores: 0xc00000100a0

There are two ways to print the memory address that the pointer points to

//The first
fmt.Printf("%p", ptr)

//The second
fmt.Println(ptr)

2. Type of pointer

We know that the type of string is string and the integer is int, so how to express the pointer?

Write a piece of code and try it out

package main

import "fmt"

func main() {
	astr := "hello"
	aint := 1
	abool := false
	arune := 'a'
	afloat := 1.2

	fmt.Printf (the "ASTR pointer type is:% t \ n", & ASTR)
	fmt.Printf ("aint pointer type is:% t \ n", & aint)
	fmt.Printf ("about pointer type is:% t \ n", & about) "
	fmt.Printf ("arune pointer type is:% t \ n", & arune)
	fmt.Printf ("afloat pointer type is:% t \ n", & afloat)
}

The output is as follows. You can find*+The data type of the pointed variable value is the corresponding pointer type.

The ASTR pointer type is: * string
Aint pointer type is: * int
About pointer type is: * bool
The arune pointer type is: * int32
Afloat pointer type is: * float64

So if we define a function that only accepts parameters of the pointer type, we can write

func mytest(ptr *int)  {
	fmt.Println(*ptr)
}

3. Zero value of pointer

When a pointer is declared, it is not initialized and its zero value is nil.

func main() {  
    a := 25
	Var b * int // declares a pointer
	
    if b == nil {
        fmt.Println(b)
        B = & A // initialization: give the memory address of a to B
        fmt.Println(b)
    }
}

The output is as follows

0xc0000100a0

4. Pointer and slice

Slices, like pointers, are reference types.

If we want to change the value of an array through a function, there are two ways

  1. Pass the slice of this array as an argument to the function
  2. Pass the pointer of this array as an argument to the function

Although both of them can achieve our goal, according to the usage habits of go language, the first method is recommended, because the code written in the first method will be more concise and easy to read. Specifically, you can code the following two methods

Using slices

func modify(sls []int) {  
	sls[0] = 90
}
	
func main() {  
    a := [3]int{89, 90, 91}
    modify(a[:])
    fmt.Println(a)
}

Use pointer

func modify(arr *[3]int) {  
	(*arr)[0] = 90
}
	
func main() {  
    a := [3]int{89, 90, 91}
    modify(&a)
    fmt.Println(a)
}

Series Guide

01. Construction of development environment (GoLand & vs Code)

02. Learn how to create five variables

03. Detailed data type: * * * * integer and floating point

04. Detailed data types: byte, run and string

05. Explain data type: array and slice

06. Explain data types: dictionary and Boolean

07. Explain data type: pointer

08. Object oriented programming: structure and inheritance

09. An article to understand the functions in go

10. Go language flow control: if else conditional statement

11. Go language process control: switch case selection statement

12. Go language process control: for loop statement

13. Go language process control: goto jump unconditionally

14. Go language process control: defer call

15. Object oriented programming: interface and polymorphism

16. Keyword: the difference between make and new?

17. An article understanding statement block and scope in go

18. Learning go process: goroutine

19. Learn go protocol: explain channel / channel in detail

20. Detailed explanation of several channel deadlock classic error cases

21. Learning go: waitgroup

22. Learning go protocol: mutex lock and read-write lock

23. Exception handling in go: panic and recover

24. Super detailed interpretation of go modules’ past life, present life and introduction

25. Eight knowledge points about package import in go language

26. How to open source the modules written by yourself for others?

27. What about type assertions in the go language?

28. These five points lead you to understand the select usage of go language