如何在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))
}

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.

Thanks for the suggestions, I believe I've found what I was looking for. It can be done, just needed to dig a little bit into the reflection package of Go. I'll answer my own question just so that somebody else might find this helpful.

The elegant one liner to get the starting memory address of any allocated block of memory as a byte pointer in Go would be:

(*byte)(unsafe.Pointer(reflect.ValueOf(anyAllocatedDataGoesHere).Pointer()))

If anybody needs to check how it will behave for any data type, i.e []uint32, []byte, string, int, struct, have a look at this sample PlayGround I prepared.

https://play.golang.org/p/G5fUOCfNCS

Depending on what your application is, you might consider Gob encoding or protobuf (as used in Brad Fitz's groupcache). You'd be making a copy of your data, and I'm pretty sure there's still reflection going on under the hood, but at least you're getting well-optimized copying & byte encoding, which may be a plus since I suspect the next step in your application once you have these bytes is a copy of some sort.