douzhao7014 2019-07-23 13:20
浏览 29
已采纳

结构切片的属性作为函数参数而不分配切片

I have a slice of structs that looks like:

type KeyValue struct {
  Key   uint32
  Value uint32
}

var mySlice []Keyvalue

This slice mySlice can have a variable length.

I would like to pass all elements of this slice into a function with this signature:

takeKeyValues(keyValue []uint32)

Now I could easily allocate a slice of []uint32, populate it with all the keys/values of the elements in mySlice and then pass that slice as an argument into takeKeyValues()...

But I'm trying to find a way of doing that without any heap allocations, by directly passing all the keys/values on the stack. Is there some syntax trick which allows me to do that?

  • 写回答

3条回答 默认 最新

  • download2014711 2019-07-23 13:42
    关注

    There is no safe way to arbitrarily reinterpret the memory layout of the your data. It's up to you whether the performance gain is worth the use of an unsafe type conversion.

    Since the fields of KeyValue are of equal size and the struct has no padding, you can convert the underlying array of KeyValue elements to an array of uint32.

    takeKeyValues((*[1 << 30]uint32)(unsafe.Pointer(&s[0]))[:len(s)*2])
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?