File tree Expand file tree Collapse file tree 1 file changed +73
-9
lines changed Expand file tree Collapse file tree 1 file changed +73
-9
lines changed Original file line number Diff line number Diff line change @@ -960,9 +960,73 @@ func main() {
960960< details>
961961< summary> 指针整数型 uintptr< /summary>
962962
963+ 用于指针运算,GC 不把 uintptr 当指针,uintptr 无法持有对象。uintptr 类型的目标会被回收。
964+
963965- uintptr
964966- 保存指正的 32 位或者 64 位整数型
965967
968+ ` ` ` go
969+ // 示例:通过指针修改结构体字段
970+ package main
971+ import (
972+ " fmt"
973+ " unsafe"
974+ )
975+
976+ func main () {
977+ s := struct {
978+ a byte
979+ b byte
980+ c byte
981+ d int64
982+ }{0, 0, 0, 0}
983+
984+ // 将结构体指针转换为通用指针
985+ p := unsafe.Pointer(& s)
986+ // 保存结构体的地址备用(偏移量为 0)
987+ up0 := uintptr(p)
988+ // 将通用指针转换为 byte 型指针
989+ pb := (* byte)(p)
990+ // 给转换后的指针赋值
991+ * pb = 10
992+ // 结构体内容跟着改变
993+ fmt.Println(s)
994+
995+ // 偏移到第 2 个字段
996+ up := up0 + unsafe.Offsetof(s.b)
997+ // 将偏移后的地址转换为通用指针
998+ p = unsafe.Pointer(up)
999+ // 将通用指针转换为 byte 型指针
1000+ pb = (* byte)(p)
1001+ // 给转换后的指针赋值
1002+ * pb = 20
1003+ // 结构体内容跟着改变
1004+ fmt.Println(s)
1005+
1006+ // 偏移到第 3 个字段
1007+ up = up0 + unsafe.Offsetof(s.c)
1008+ // 将偏移后的地址转换为通用指针
1009+ p = unsafe.Pointer(up)
1010+ // 将通用指针转换为 byte 型指针
1011+ pb = (* byte)(p)
1012+ // 给转换后的指针赋值
1013+ * pb = 30
1014+ // 结构体内容跟着改变
1015+ fmt.Println(s)
1016+
1017+ // 偏移到第 4 个字段
1018+ up = up0 + unsafe.Offsetof(s.d)
1019+ // 将偏移后的地址转换为通用指针
1020+ p = unsafe.Pointer(up)
1021+ // 将通用指针转换为 int64 型指针
1022+ pi := (* int64)(p)
1023+ // 给转换后的指针赋值
1024+ * pi = 40
1025+ // 结构体内容跟着改变
1026+ fmt.Println(s)
1027+ }
1028+ ` ` `
1029+
9661030< /details>
9671031
9681032< details>
@@ -1927,10 +1991,10 @@ func main() {
19271991package main
19281992import " fmt"
19291993func main () {
1930- // 2. 在输出 world
1931- defer fmt.Println(" world" )
1932- // 1. 先输出 hello
1933- fmt.Println(" hello" )
1994+ // 2. 在输出 world
1995+ defer fmt.Println(" world" )
1996+ // 1. 先输出 hello
1997+ fmt.Println(" hello" )
19341998}
19351999` ` `
19362000
@@ -1945,11 +2009,11 @@ func main() {
19452009package main
19462010import " fmt"
19472011func main () {
1948- fmt.Println(" counting" )
1949- for i := 0; i < 10; i++ {
1950- defer fmt.Println(i)
1951- }
1952- fmt.Println(" done" )
2012+ fmt.Println(" counting" )
2013+ for i := 0; i < 10; i++ {
2014+ defer fmt.Println(i)
2015+ }
2016+ fmt.Println(" done" )
19532017}
19542018` ` `
19552019
You can’t perform that action at this time.
0 commit comments