gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/unsafe/test-offset/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"gitee.com/sy_183/go-common/unit"
     6  	unsafeUtil "gitee.com/sy_183/go-common/unsafe"
     7  	"unsafe"
     8  )
     9  
    10  func test(a, b int) int {
    11  	return a + b
    12  }
    13  
    14  func main() {
    15  	type st struct {
    16  		A string
    17  		B int
    18  		C bool
    19  		D float64
    20  		E []byte
    21  	}
    22  	s := st{
    23  		A: "a",
    24  		B: 1,
    25  		C: true,
    26  		D: 3.14,
    27  		E: []byte{1, 2, 3, 4},
    28  	}
    29  	var c int
    30  	for i := 0; i < unit.GiBiByte; i++ {
    31  		s.B = i
    32  		if b := unsafeUtil.Offset[st, int](&s, unsafe.Offsetof(s.B)); b != i {
    33  			panic(fmt.Sprintf("%d != %d", b, i))
    34  		}
    35  		c = test(1, i)
    36  	}
    37  	fmt.Println(c)
    38  }