douchuza8908 2016-06-08 10:00
浏览 59
已采纳

在Go中存储/访问嵌套数据-使用结构吗?

I need to maintain some data internally in my go code: an ID nested multiple levels deep, which is to be accessed when the names of the parent props are provided. If writing in JavaScript for example, I'd do something like:

var data = {
    1111: {
        la1: {
            lb1: 1343584765,
            lb2: 1545438458
        },
        la2: {
            lb1: 1263268535,
            lb2: 1468904679
        }
    },
    2222: {
        la1: {
            lb1: 1645078365,
            lb2: 1457732458
        },
        la2: {
            lb1: 1682974682,
            lb2: 1782975685
        }
    }
}

and then access like this (yes the top prop needs to be an int):

data[1111]['la1']['la2'] //gets 1343584765

but I can't see how to build this structure with Go structs, and most things I read advise against doing it that way. The only other way I can see is to use this logic in Go, but it feels messy and this may get bigger and therefore hard to maintain:

func getVal(
    varA int,
    varB string,
    varC string,
) int {
    if varA == 1111 {
        if varB == "la1" {
            if varC == "lb1" {
                return 1343584765
            }
            if varC == "lb2" {
                return 1545438458
            }
        }
        if varB == "la2" {
            if varC == "lb1" {
                return 1263268535
            }
            if varC == "lb2" {
                return 1468904679
            }
        }
    }
    if varA == 2222 {
    ....etc

and then access with:

getVal(1111, "la1", "lb1") //gets 1343584765

Big thanks to anyone who can help me out a bit!

  • 写回答

1条回答 默认 最新

  • dongtangu8403 2016-06-08 12:53
    关注

    Your way of approaching the problem is very peculiar. Maybe you already know this but on the off-chance you don't: use maps.

    I made an example with badly-named types (since I don't know your use-case) and I also made everything a string to keep it simple.

    type l3Map map[string]string
    type l2Map map[string]l3Map
    type l1Map map[string]l2Map
    
    func main() {
    
        data := l1Map{
            "1111": l2Map{
                "la1": l3Map{
                    "lb1": "1343584765",
                    "lb2": "1545438458",
                },
            },
        }
    
        fmt.Printf("%v
    ", data["1111"]["la1"]["lb2"])
    }
    

    https://play.golang.org/p/daKjDbX8Ao

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失