1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
| package main
import (
"fmt"
"math/bits"
"reflect"
"unsafe"
)
var (
i8 int8
u8 uint8
i16 int16
u16 uint16
i32 int32
u32 uint32
i64 int64
u64 uint64
i int
u uint
)
type student struct {
name string
age int
}
func main() {
fmt.Printf("i8: %d bits, %s type, %d bytes\n", bits.UintSize, reflect.TypeOf(i8), unsafe.Sizeof(i8))
fmt.Printf("u8: %d bits, %s type, %d bytes\n\n", bits.UintSize, reflect.TypeOf(u8), unsafe.Sizeof(u8))
fmt.Printf("i16: %d bits, %s type, %d bytes\n", bits.UintSize, reflect.TypeOf(i16), unsafe.Sizeof(i16))
fmt.Printf("u16: %d bits, %s type, %d bytes\n\n", bits.UintSize, reflect.TypeOf(u16), unsafe.Sizeof(u16))
fmt.Printf("i32: %d bits, %s type, %d bytes\n", bits.UintSize, reflect.TypeOf(i32), unsafe.Sizeof(i32))
fmt.Printf("u32: %d bits, %s type, %d bytes\n\n", bits.UintSize, reflect.TypeOf(u32), unsafe.Sizeof(u32))
fmt.Printf("i64: %d bits, %s type, %d bytes\n", bits.UintSize, reflect.TypeOf(i64), unsafe.Sizeof(i64))
fmt.Printf("u64: %d bits, %s type, %d bytes\n\n", bits.UintSize, reflect.TypeOf(u64), unsafe.Sizeof(u64))
fmt.Printf("i: %d bits, %s type, %d bytes\n", bits.UintSize, reflect.TypeOf(i), unsafe.Sizeof(i))
fmt.Printf("u: %d bits, %s type, %d bytes\n\n", bits.UintSize, reflect.TypeOf(u), unsafe.Sizeof(u))
s := &student{name: "tony", age: 18}
// Get the address of field name in struct s
p := unsafe.Pointer(uintptr(unsafe.Pointer(s)) + unsafe.Offsetof(s.name))
// Typecast it to a string pointer and print the value of it
fmt.Printf("p: %s", *(*string)(p))
}
/*
i8: 64 bits, int8 type, 1 bytes
u8: 64 bits, uint8 type, 1 bytes
i16: 64 bits, int16 type, 2 bytes
u16: 64 bits, uint16 type, 2 bytes
i32: 64 bits, int32 type, 4 bytes
u32: 64 bits, uint32 type, 4 bytes
i64: 64 bits, int64 type, 8 bytes
u64: 64 bits, uint64 type, 8 bytes
i: 64 bits, int type, 8 bytes
u: 64 bits, uint type, 8 bytes
p: tony
*/
|