2017-06-12 47 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函數在您需要的任何尺寸的循環中。