dongxi5494 2016-10-05 22:46
浏览 44
已采纳

Golang结构定义模式

I'm currently playing with Go, was wondering what are the patterns for defining the data types. For example take the Bencode and representing it as a Go data structure.

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;

what is the best way to define these kinds of data structures in Golang. Are there any patterns / good practices with Golang.

  • 写回答

1条回答 默认 最新

  • douwen8424 2016-10-06 04:21
    关注

    Like this?

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化