2016-10-05 22 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内のデータ構造のこれらの種類を定義するための最良の方法は何ですか。ゴランとパターン/良い練習がありますか?

+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 
}