doue9730 2016-10-30 12:47 采纳率: 100%
浏览 247

如何在Golang中获取指向任何数据类型的值的字节指针?

I've managed to get the following function working in Go. But I want to optimize/generalize the code such that this function would return me a pointer to the first byte of any value I pass into the function. Currently it will only work for []uint32, but I want to use it to get the starting memory address as a *byte for many other types (i.e. byte[], int[], string, etc).

Is there a more generic way to do this rather than catching every single type I need to address as case statements?

Go Playground Link for below code: https://play.golang.org/p/KtNTbERQGa

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

func ToBytePointer(data interface{}) *byte {
    fmt.Println("Received type is", reflect.TypeOf(data))

    switch data.(type) {
    case []uint32:
        typedData := data.([]uint32)
        return (*byte)(unsafe.Pointer(&typedData[0]))
    default:
        return nil
    }
}

func main() {
    var data = []uint32{1, 2, 3}
    var dataBytePointer = (*byte)(unsafe.Pointer(&data[0]))

    fmt.Println(dataBytePointer, ToBytePointer(data))
}
  • 写回答

3条回答 默认 最新

  • duanjianfu1398 2016-10-30 14:41
    关注

    Golang does not have generics, so I guess you need to catch every single type.

    Also, in your example, you got the first byte of the first element in the slice, not the first byte of the value passed to the function.

    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多