首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Golang结构定义模式

Golang结构定义模式
EN

Stack Overflow用户
提问于 2016-10-05 22:46:57
回答 1查看 607关注 0票数 0

我目前正在玩Go,我想知道定义数据类型的模式是什么。例如,以本码为例,并将其表示为Go数据结构。

就像在哈斯克尔

代码语言:javascript
复制
data BEncode = BInt Integer
         | BString L.ByteString
         | BList [BEncode]
         | BDict (Map String BEncode)

在C语言中,我们可以这样做

代码语言:javascript
复制
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是否有任何模式/良好做法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-06 04:21:45

是像这样吗?

代码语言:javascript
复制
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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39884835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档