2016-10-05 73 views
0

我目前在玩Go,想知道什麼是定義數據類型的模式。例如採取Bencode並將其表示爲Go數據結構。Golang結構定義模式

like in Haskell

data BEncode = BInt Integer 
     | BString L.ByteString 
     | BList [BEncode] 
     | BDict (Map String BEncode) 

in C, we can do something like this

struct Bencoding; 

typedef struct ListNode { 
    struct Bencoding *cargo; 
    struct ListNode *next; 
} ListNode; 

typedef struct DictNode { 
    char *key; 
    struct Bencoding *value; 
    struct DictNode *next; 
} DictNode; 

typedef struct Bencoding { 
    BType type; 
    union { 
     long long val; // used when type == BInt 
     ListNode *list; // used when type == BList 
     char *str;  // used when type == BString 
     DictNode *dict; 
    } cargo; // data 
} Bencoding; 

是什麼Golang定義這些類型的數據結構的最佳方式。 Golang是否有任何模式/良好做法?

+2

結構是在圍棋的唯一對象類型和他們遵循大多數的規則相同C.如果你有足夠的知識請你也應該知道,足以找到答案的問題。 – evanmcdonnal

回答

0

是否這樣?

type BEncodeType int 

const (
    TypeBInt BEncodeType = iota 
    TypeBString 
    TypeBList 
    TypeBDict 
) 

type BEncode interface { 
    Type() BEncodeType 
    Val() interface{} 
} 

type BInt int 

func (n *BInt) Type() BEncodeType { 
    return TypeBInt 
} 
func (n *BInt) Val() interface{} { 
    return n 
} 

type BString string 

func (n *BString) Type() BEncodeType { 
    return TypeBString 
} 
func (n *BString) Val() interface{} { 
    return n 
} 

type BList []BEncode 

func (n *BList) Type() BEncodeType { 
    return TypeBList 
} 
func (n *BList) Val() interface{} { 
    return n 
} 

type BDict map[string]BEncode 

func (n *BDict) Type() BEncodeType { 
    return TypeBDict 
} 
func (n *BDict) Val() interface{} { 
    return n 
}