Golang 将 interface{} 转换为 N 大小的数组

Golang convert interface{} to array of N size

我有一个包含在接口中的 T 数组。我事先知道数组的大小。如何编写一个通用函数来返回任意数组长度的数组(或切片)?例如。对于尺寸 3,我想要

var values interface{} = [3]byte{1, 2, 3}
var size = 3 // I know the size

var _ = values.([size]byte) // wrong, array bound must be a const expression

我真的无法进行类型转换,因为 [1]byte[2]byte 等不同,所以我必须明确枚举所有可能的大小。

反映是你的朋友:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var in interface{} = [3]byte{1, 2, 3} // an element from your []interface{}
    var size = 3                          // you got this
    out := make([]byte, size)             // slice output

    for i := 0; i < size; i++ {
        idxval := reflect.ValueOf(in).Index(i) // magic here
        uidxval := uint8(idxval.Uint())        // you may mess around with the types here
        out[i] = uidxval                       // and dump in output
    }

    fmt.Printf("%v\n", out)
}

这里切片是更好的选择输出,因为你指出你有一个未定义的长度。 Magic 在这里做的是通过 reflect 索引你的输入接口的值。这不是很快,但可以解决问题。