Pointers 将指针保存到golang中的字符串数据结构中
我有一个只接受字符串的数据结构,我想存储指向另一个数据结构的指针 因此,我可以将指针保存为字符串:Pointers 将指针保存到golang中的字符串数据结构中,pointers,go,casting,Pointers,Go,Casting,我有一个只接受字符串的数据结构,我想存储指向另一个数据结构的指针 因此,我可以将指针保存为字符串: ptr := fmt.Sprint(&data) // ptr is now something like : 0xc82000a308 然后,稍后我想在ptr上获得stuff store,有没有办法将此ptr转换为指针类型?当然,可以使用不安全的包: 但是,请记住不安全包装上的各种警告。例如: uintptr是整数,不是引用。将指针转换为uintptr会创建一个没有指针语义的整数值。
ptr := fmt.Sprint(&data) // ptr is now something like : 0xc82000a308
然后,稍后我想在ptr上获得stuff store,有没有办法将此ptr转换为指针类型?当然,可以使用不安全的包: 但是,请记住不安全包装上的各种警告。例如:
uintptr是整数,不是引用。将指针转换为uintptr会创建一个没有指针语义的整数值。即使uintptr保留某个对象的地址,垃圾收集器也不会在对象移动时更新该uintptr的值,uintptr也不会阻止对象被回收-永远不要那样做。这是可能的,但您的代码将中断,因为GC将看不到您的字符串化指针,并且可能会收集内容。
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...")
}
}