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 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计