Previous articles in the Go Primer series:

  • Go language introduction series (2) basic syntax summary
  • Arrays and slicing in Go primer series 3
  • The use of Map in Go Introduction series 4

Pointer to 1.

If you’ve ever used C or C++, you’re no doubt familiar with the concept of Pointers.

We need to introduce two concepts first: memory and address.

1.1. Memory and address

The code we write is stored in external storage (drive C, drive D). For example, I saved it in the D:\Work\Program\ Go directory. If you want to run your code, you must first load your code into memory, and then give it to the CPU to perform the calculation, and the CPU will store the result in memory.

Memory access speed, there are many storage units used to store data, CPU can directly find the data in the memory. This is because each location in memory has a unique address identifier. Think of memory as a building with many rooms. Each storage unit is a room. The data stored is the item in the room, and the address is the room number.

So for the CPU, if we want to find an item in a room (fetch data from memory) or put an item in a room (store data into memory), we must know the room number (memory address).

The memory address is usually a string of hexadecimal numbers, which is too cumbersome to write code that requires either storing an integer 1 or retrieving an integer 1. So high-level languages provide us with the convenience of replacing numbers with “names” that we can remember.

These “names” are the variable names.

var a int = 1
var b int = 2
var c int = 333
var d int = 6666
Copy the code

The compiler does the association between variable names and addresses for us, and the hardware still accesses memory addresses.

1.2. What are Pointers?

In simple terms, a pointer is also a variable, except that instead of the 1, 2, 3, “Hello”, and true values we normally use, it contains the addresses of other variables.

We call it pointer because pointer variable B holds the address of variable A, and we can find variable A through pointer variable B, and if we draw it, it looks like pointer B points to variable A.

Pointers can also have Pointers:

1.3. Use of Pointers

Declare a pointer:

var p *int
Copy the code

*int indicates that p is an int pointer, and p holds the address of a variable of int, meaning that p cannot hold the address of any variable of other types.

How do I get the address of a variable? Use the & : operator

var a int = 66 //a is an int with a value of 66
p = &a // Assign the address of a to pointer p
Copy the code

So how do you find the corresponding variable based on the address in the pointer? Use the operator * :

var b = *p // Find a from p and assign its value to B
fmt.Println(b) / / 66

*p = 99 // Select a from p and change a
fmt.Println(a) / / 99
Copy the code

Be careful when initializing Pointers. If not, the value of a pointer is nil. Assigning to an uninitialized pointer causes a problem:

var p *int // Only declare, not initialize
*p = 12 // Invalid memory address or nil pointer dereference
Copy the code

The reason is that pointer P has no value in it, it’s nil, so you can’t find variables by address. ** If you want to use Pointers, you must make sure that your Pointers have a valid memory address. ** should read:

var a int
var p *int = &a //p is initialized to the address of A
*p = 12 // select a from p and assign 12 to a
/ / or
var a int
var p *int
p = &a //a's address is assigned to p
*p = 12 // select a from p and assign 12 to a
Copy the code

Here is a complete example:

package main

import "fmt"

func main(a) {
	var a int = 66 / / variable a
	var p *int = &a // the pointer p points to a
	var b = *p // Get the value of variable A pointed to by p
	fmt.Println("a =",a, ", b =", b, ", p =", p)
	fmt.Println("A's address =", &a, ", b's address =", &b, ", p's address =", &p)

	*p = 12 // Change the value of variable a pointed to by p

	fmt.Println("a =",a, ", b =", b, ", p =", p)
	fmt.Println("A's address =", &a, ", b's address =", &b, ", p's address =", &p)

	var pp **int = &p // pointer pp points to pointer p
	var c = *pp // get the value of p that pp points to
	var d = **pp // get the value of pp to p to A
	fmt.Println("pp =", pp, ", c =", c, ", d =", d)
	fmt.Println("Address of pp =", &pp, ", address of c =", &c, ", address of d =", &d)
}
Copy the code

2. Struct

2.1. Basic usage

Like C, Go has constructs.

A structure is a collection of fields/attributes. With structures, we can define our own types according to our own needs. A dog, for example, cannot be represented as a basic data type because it has many attributes: a string name, an int age, and so on. A dog is a collection of attributes. In other words, a dog is a structure. We can define a dog-type structure to represent a dog.

Structure declaration:

typeStructure namestruct{the field name1type1The field name2type2. }Copy the code

Here is the declaration for the dog structure:

type dog struct {
    name string
    age int
}
Copy the code

Once you have declared the structure, you can use it.

First, as long as you declare the structure correctly, you can declare variables of type dog in the same way you would declare variables of primitive types like int or string, and then you can assign values to the fields of declared variable D, with a dot. To access the struct’s fields:

var d dog // declare a variable d of type dog
d.name = Crouching Dog
d.age = 3
Copy the code

In addition, there are several ways to declare.

You can assign directly in field order

d := dog{Crouching Dog.3}
Copy the code

Or specify field assignment so that the field order can be ignored:

d := dog{age:3, name:Crouching Dog}
Copy the code

Here is a complete example:

package main

import "fmt"

type dog struct {
	name string
	age int
}

func main(a) {
	var d dog // declare a variable d of type dog
	d.name = Crouching Dog
	d.age = 3

	d1 := dog{Croup Dog.2}
	
	d2 := dog{age:4, name:Croup Dog}

	fmt.Println(d, d1, d2)
}
Copy the code

2.2. Structure pointer

We can get a pointer to a structure:

d := dog{Croup Dog.2}
p := &d // Get the address of d
Copy the code

You can access its fields according to the structure pointer:

n := (*p).name
fmt.Println(n) / / xiao days dog
Copy the code

This is cumbersome, and the Go language provides implicit indirect references:

n := p.name // This is ok
fmt.Println(n)
Copy the code

We can assign a pointer to a structure using the new function.

Let’s start with the new function: The new function allocates various types of memory. New (T) allocates the appropriate memory space for type T, fills it with zero values of type T, and returns its address, which is a *T value. In other words, the function returns a pointer to a zero value of type T.

p := new(dog)
fmt.Printf("%T\n", p) //*main.dog
fmt.Println(p) / / & {0}
fmt.Println(*p) / / {0}
Copy the code

As you can see from the three lines printed above, new(dog) returns a pointer.

2.3. Structure nesting

A structure can also be a field of another structure. Here is an example:

package main

import "fmt"

type people struct {
	name string
	age int
	d dog
}

type dog struct {
	name string
	age int
}

func main(a) {
	a := people{"Little view of action".18, dog{"The dog".2}}
	fmt.Println(a) //{line small view 18 {dog 2}}
	fmt.Println(a.d) / / {2} the dog
	fmt.Println(a.name) / / in line
	fmt.Println(a.d.name) / / the dog
}
Copy the code

You can also use anonymous fields. What are anonymous fields? As the name implies, provide only the type, not the field name:

package main

import "fmt"

type people struct {
	name string
	age int
	dog // Anonymous field
}

type dog struct {
	name string
	age int
}

func main(a) {
	a := people{"Little view of action".18, dog{"The dog".2}}
	fmt.Println(a) //{line small view 18 {dog 2}}
	fmt.Println(a.dog) / / {2} the dog
	fmt.Println(a.name) / / in line
	fmt.Println(a.dog.name) / / the dog
}
Copy the code

Author’s brief introduction

I am “Xing Xiao Guan”, an ordinary person among thousands of people. I went down the programming path by mistake, and I went down that path as far as I could.

I will continue to update “Java”, “Go”, “Data Structure and Algorithm”, “Computer Fundamentals” and other related articles in the public account “Pedestrian View”.

Welcome attention, we set foot on the journey together.

This article is part of a series called Introduction to the Go language.

Please correct me if there are any mistakes.