本文主要是介绍Go_unsafe包,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
是什么?为什么?
如何利用unsafe包修改私有成员?
结构体会被分配到一块连续的内存,结构体的地址也代表第一个成员的地址。
如何利用unsafe包获取slice和map的长度?
// 利用unsafe包修改私有成员
type S struct {name stringlanguage stringage int
}func main() {s := S{name: "张三",language: "英语",age: 4,}name := (*string)(unsafe.Pointer(&s))*name = "qcrao"lang := (*string)(unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.language)))*lang = "Golang"age := (*int)(unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.age)))*age = 1fmt.Println(s)
}
// 利用unsafe获取切片和map的长度.
func main() {s := make([]int, 9, 20)var Len = *(*int)(unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + uintptr(8)))fmt.Println(Len, len(s)) // 9 9var Cap = *(*int)(unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + uintptr(16)))fmt.Println(Cap, cap(s)) // 20 20mp := make(map[string]int)mp["qcrao"] = 100mp["stefno"] = 18count := **(**int)(unsafe.Pointer(&mp))fmt.Println(count, len(mp)) // 2 2
}
这篇关于Go_unsafe包的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!