如何使用反射制作多维数组或切片

时间:2017-06-12 19:27:21

标签: arrays go multidimensional-array reflection slice

我目前正在开发一个项目,在Go中为另一种利用多维数组的语言创建一个绑定。我正试图找到一种动态的方法,可以创建一个切片或具有多个维度的数组数组。我目前正在查看反射文档,但没有任何内容在我身上跳出来,这似乎是一种直观的方法来完成我需要做的事情。

对于上下文,我可以获取类型信息并将其解析为此结构:

const (
    IntTy byte = iota
    UintTy
    BoolTy
    StringTy
    AddressTy
    HashTy
    FixedPointTy
    FunctionTy
    FixedBytesTy
    StaticArrayTy
    DynamicArrayTy
    MultiDimensionalArrayTy
    StructTy
    BytesTy
)

// Type is the reflection of the supported argument type
type Type struct {
    // Slice descriptions
    IsStatic           bool // Determines if its a static array
    IsDynamic          bool // Determines if its a dynamic array
    IsMultiDimensional bool // Determine if there is more than dimension to the array
    SliceSize          int  // Size of the slice if it's static
    Dimensions         int  // Number of dimensions if type is a multidimensional array

    // If applicable (struct, slice), the underlying type
    Elem *Type

    Kind           reflect.Kind // corresponding go Kind.
    Type           reflect.Type // corresponding go Type.
    Size           int          // type size (denotes uint256, uint248, etc.)
    T              byte         // Our own type checking
    RequiresOffset bool         // denotes whether the type needs an offset

    stringKind string // holds the unparsed string for deriving signatures
}

请注意,有些字段用于帮助描述切片和基础类型(我们希望尽可能准确)。我有一个类型字节以及表示切片的元素数量和尺寸的元素。但是从这些描述中创建golang多维切片类型的直观方法是什么?一个算法展示了这一点,例如a [] [] uint或[] [] [] uint将非常感激。

1 个答案:

答案 0 :(得分:0)

好吧,我想我第一次没有看得太辛苦,但回想起来答案很明显。我在这里使用这个Go Playground做了一个例子:https://play.golang.org/p/J0pAGNIpDX

ICYMI,基本方法是获取您正在使用的类型的类型(基本类型),然后在循环中的类型上运行SliceOf / ArrayOf函数,以获得所需的多个维度。