doutui839638 2016-06-23 20:41
浏览 53
已采纳

将指针保存到golang中的String数据结构中

This question already has an answer here:

I have a data structure that only accepts strings and I want to store pointers to another data structure.

Enssentially I can save the pointers as string as such:

ptr := fmt.Sprint(&data) // ptr is now something like : 0xc82000a308

then later on I want to get the stuff store at the ptr, is there a way to cast this ptr to a pointer type?

</div>
  • 写回答

1条回答 默认 最新

  • douchigu1723 2016-06-23 21:22
    关注

    Sure, you can do that using the unsafe package:

    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
    ", 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...")
        }
    }
    

    However, keep in mind the various warnings on the unsafe package. For example:

    "A uintptr is an integer, not a reference. Converting a Pointer to a uintptr creates an integer value with no pointer semantics. Even if a uintptr holds the address of some object, the garbage collector will not update that uintptr's value if the object moves, nor will that uintptr keep the object from being reclaimed." - https://golang.org/pkg/unsafe/#Pointer

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?