Nic*_*ler 3 pointers casting go
我有一个仅接受字符串的数据结构,并且我想存储指向另一个数据结构的指针。
本质上我可以将指针保存为字符串,如下所示:
ptr := fmt.Sprint(&data) // ptr is now something like : 0xc82000a308
Run Code Online (Sandbox Code Playgroud)
然后后来我想获取 ptr 上的东西存储,有没有办法将此 ptr 转换为指针类型?
当然,您可以使用不安全的包来做到这一点:
https://play.golang.org/p/Wd7hWn9Zsu
package main
import (
"fmt"
"strconv"
"unsafe"
)
func main() {
//Given:
data := "Hello"
ptrString := fmt.Sprintf("%d", &data)
//Convert it to a uint64
ptrInt, _ := strconv.ParseUint(ptrString, 10, 64)
//They should match
fmt.Printf("Address as String: %s as Int: %d\n", ptrString, ptrInt)
//Convert the integer to a uintptr type
ptrVal := uintptr(ptrInt)
//Convert the uintptr to a Pointer type
ptr := unsafe.Pointer(ptrVal)
//Get the string pointer by address
stringPtr := (*string)(ptr)
//Get the value at that pointer
newData := *stringPtr
//Got it:
fmt.Println(newData)
//Test
if(stringPtr == &data && data == newData) {
fmt.Println("successful round trip!")
} else {
fmt.Println("uhoh! Something went wrong...")
}
}
Run Code Online (Sandbox Code Playgroud)
但是,请记住不安全包装上的各种警告。例如:
“uintptr 是一个整数,而不是引用。将指针转换为 uintptr 会创建一个没有指针语义的整数值。即使 uintptr 保存某个对象的地址,如果该对象移动,垃圾收集器也不会更新该 uintptr 的值, uintptr 也不会阻止对象被回收。” - https://golang.org/pkg/unsafe/#Pointer