2017-06-12 130 views
0

我目前正在开发一个项目,以便在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多维片段类型的直观方式是什么?我们将非常感谢一种演示[] [] uint或[] [] [] uint的算法。

回答

0

好吧,我想我第一次看起来不够辛苦,但回过头来看,答案很明显。我在这里举了一个使用Go Go Playground的例子:https://play.golang.org/p/J0pAGNIpDX

ICYMI,基本的方法是采用你正在使用的类型的类型(基类型),然后在类型上运行SliceOf/ArrayOf函数在您需要的任何尺寸的循环中。