How to understand the map and pointer of Go language
This article focuses on "how to understand the map and pointers of the Go language". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to understand the map and pointers of the Go language.
Example:
Rec1: = make (map [string] int)
Rec1 ["width"] = 1
Rec1 ["height"] = 3
The effects of the above two declarations and initialization methods are the same, and they are selected according to the actual situation. Try visiting a Key that doesn't exist and see what happens.
Fmt.Println (rec ["point"])
The result will output: 0, will not report an error! It returns the default value of int: 0.
Does Key exist?
So how to tell whether a Key exists or not? This can be achieved as follows:
If val, ok: = rec ["point"]; ok {
Fmt.Println (val)
} else {
Fmt.Println ("key point not exists")
}
Ergodic
For k, v: = range rec {
Fmt.Println (k, "=", v)
}
Delete Key
Delete (rec, "width")
If val, ok: = rec ["width"]; ok {
Fmt.Println (val)
} else {
Fmt.Println ("key width has been deleted")
}
Pointer
One of the authors of Go is Thompson, who invented the B programming language that later derived the C language. as the ancestor, a new language pointer must be designed. The pointer syntax in Go is basically the same as the pointer syntax in C, except that the pointer cannot be arithmetic in Go.
Func pointers () {
X: = new (int)
* x = 2
Fmt.Println (reflect.TypeOf (x), * x, x)
Y: = 2
Fmt.Println (& y, reflect.TypeOf (& y), reflect.TypeOf (y))
PointParam & y
}
Func pointerParam (p * int) {
Fmt.Println (reflect.TypeOf (p), p, * p)
}
The above new can be thought of as the malloc in C, allocates the corresponding memory space for the type, and then returns the pointer to the corresponding memory, that is, the memory address. The new function is equivalent to the following function:
Func newInt () * int {
Var i int
Return & I
}
X: = newInt ()
At this point, I believe you have a deeper understanding of "how to understand the map and pointers of the Go language". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!