douwan4993 2016-01-11 03:19
浏览 55

在Go中存储和迭代命名嵌套数据结构的惯用方式?

My question is split into two: (1) what's the best way to store the data for taskList below, and (2) what's the best way to iterate over such a structure?

I want the task1 named because they are unique tasks and there shouldn't be an ID collision. I want individually named subtask0 because they are unique tasks with different requirements.

Below is a pseudo-Go representation of my intention:

package main

import "fmt"

fn main() {
    const taskList := {
        "task1": {
            "subtask0": "api.example.com/stuff/"
            "subtask1": "api.example.com/stuff/"
            "subtask2": "api.example.com/stuff/"
        }
        "task2": { 
            "subtask0": "api.example.com/stuff/"
            "subtask1": "api.example.com/stuff/"
            "subtask2": "api.example.com/stuff/"
        }
    }

    for i := range taskList {
        for j := range taskList[i] {
            fmt.Printf("%s
", taskList[i][j])
        }
    }
}

I've tried struct, but I had difficulty iterating over the struct. I wanted to avoid map because Go wouldn't let me store it in a const.

  • 写回答

1条回答 默认 最新

  • dongzi0850 2016-01-11 03:43
    关注

    Based on what I saw in your pseudocode and based on what I heard from the comments, I would go with slice of slices of struct:

    So I would define a struct:

    type subtask struct {
        name string
        kind int
    }
    

    where name would be your api.example.com/stuff/ and kind would be a type of your subtask:

    I will be treating them differently (some API's want different headers)

    Then your list would look like this:

    list := [][]subtask{
        []subtask{subtask{"example1", 1}, subtask{"example2", 1}},
        []subtask{subtask{"example3", 1}, subtask{"example4", 2}},
    }
    

    And fully working example is here <kbd>Playground</kbd>

    评论

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计