如何设计一个数据结构,可以同时容纳 string, bool, []string, 嵌套的 []string

ssqq · 2017-08-18 18:16:45 · 2831 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2017-08-18 18:16:45 的主题,其中的信息可能已经有所发展或是发生改变。

处理语法树时,需要这样的数据结构,可以返回:

string 'string'
bool    true/false
[]string ['name', 'value']
嵌套的切片  ['name', ['name', 'string']]

不知要如何设计这个数据结构呢?


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2831 次点击  
加入收藏 微博
5 回复  |  直到 2017-08-20 04:41:24
channel
channel · #1 · 8年之前

用一个字段标识类型,一个字段存具体的值

ssqq
ssqq · #2 · 8年之前

这是个不错的思路,但数据类型太多,似乎有些太浪费内存了。

type atom struct {
    type   string
    str      string
    bool   boolean
    array  []string
    atoms []atom
    name string
    value  atom
}

switch atom.type {
    case 'str' : atom.str;
    case 'true' : atom.bool
    case 'array': atom.array
    case 'atoms': atom.atoms
    case 'atom', name := atom.name; value := atom.value
}
ssqq
ssqq · #3 · 8年之前

格式乱了,不知道多行代码怎么设置

channel
channel · #4 · 8年之前

觉得浪费内存,那值就用 interface 存,可以容纳任何值

ssqq
ssqq · #5 · 8年之前

我打算用字符串来模拟这些数据,然后串联起来,可以很容易的遍历,很容易的增长,速度也很快。

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传