Example analysis of pointer operation in Go language

  • 2020-05-26 09:16:49
  • OfStack

This paper analyzes the pointer operation method in Go. Share with you for your reference. The specific analysis is as follows:

The Go language does not support pointer arithmetic syntactically, all Pointers are used in a range that is controllable, there is no *void in C and then you can convert pointer types and things like that. Recently I was thinking about how Go operates on Shared memory. Shared memory needs to convert the pointer to a different type or operate on the pointer to get data.

Here is an experiment on unsafe module built into Go language. It is found that through unsafe module, Go language 1 can do pointer operation, but it is more complicated than C.

Here is the experimental code:

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 execution results of the above code on my machine are as follows (the results will vary depending on the machine and system) :
32
----
1
4
8
4
----
0
4
8
24
----
32
----
98
77
1234567890abcdef
23

There are several conversion rules mentioned in the unsafe module's documentation, which make it easy to perform pointer operations once you understand them:

A pointer value of any type can be 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 has been helpful to you in the programming of Go language.


Related articles: