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 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。