我目前正在玩Go,我想知道定义数据类型的模式是什么。例如,以本码为例,并将其表示为Go数据结构。
data BEncode = BInt Integer
| BString L.ByteString
| BList [BEncode]
| BDict (Map String BEncode)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是否有任何模式/良好做法。
发布于 2016-10-06 04:21:45
是像这样吗?
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
}https://stackoverflow.com/questions/39884835
复制相似问题