In this paper, we analyze the pointer arithmetic in go language. Share to everyone for your reference. The specific analysis is as follows:
The grammar of the Go language does not support pointer arithmetic, all pointers are used in a controllable range, there is no C language *void and then arbitrarily converts the pointer type such things. Recently, thinking about how go operates shared memory, shared memory needs to turn pointers to different types or to manipulate pointers and retrieve data.
This is an experiment with the unsafe module built into the go language, and it is found that, as with the unsafe module, you can do pointer operations just as much as C, but it is the same as the way it is understood.
Here is the experimental code:
Copy Code code as follows:
Package Main
Import "FMT"
Import "unsafe"
Type Data struct {
Col1 byte
Col2 int
Col3 string
COL4 int
}
Func Main () {
var v Data
Fmt. Println (unsafe. Sizeof (v))
Fmt. PRINTLN ("----")
Fmt. Println (unsafe. Alignof (V.COL1))
Fmt. Println (unsafe. Alignof (V.col2))
Fmt. Println (unsafe. Alignof (V.COL3))
Fmt. Println (unsafe. Alignof (V.COL4))
Fmt. PRINTLN ("----")
Fmt. Println (unsafe. Offsetof (V.COL1))
Fmt. Println (unsafe. Offsetof (V.col2))
Fmt. Println (unsafe. Offsetof (V.COL3))
Fmt. Println (unsafe. Offsetof (V.COL4))
Fmt. PRINTLN ("----")
V.col1 = 98
V.col2 = 77
V.col3 = "1234567890abcdef"
V.col4 = 23
Fmt. Println (unsafe. Sizeof (v))
Fmt. PRINTLN ("----")
x: = unsafe. Pointer (&v)
Fmt. Println (* (*byte) (x))
Fmt. Println (* (*int) (unsafe. Pointer (uintptr (x) + unsafe. Offsetof (v.col2)))
Fmt. Println (* (*string) (unsafe. Pointer (uintptr (x) + unsafe. Offsetof (V.COL3)))
Fmt. Println (* (*int) (unsafe. Pointer (uintptr (x) + unsafe. Offsetof (V.COL4)))
}
The results of the above code on my machine are as follows (the result will vary from machine to system):
32
----
1
4
8
4
----
0
4
8
24
----
32
----
98
77
1234567890abcdef
23
There are several conversion rules mentioned in the documentation for the unsafe module, which makes it easy to do pointer operations after understanding:
A pointer value of any type can is converted to a pointer.
A pointer can be converted to a pointer value of any type.
A uintptr can be converted to a pointer.
A pointer can be converted to a uintptr.
I hope this article will help you with your go language program.