英文:
Idiomatic way to store and iterate over a named nested data structure in Go?
问题
我的问题分为两部分:(1)如何最好地存储下面的taskList数据,(2)如何最好地迭代这样的结构?
我希望task1
有名称,因为它们是唯一的任务,不应该有ID冲突。我希望每个subtask0
都有独立的名称,因为它们是具有不同要求的唯一任务。
以下是我意图的伪Go表示:
package main
import "fmt"
func 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\n", taskList[i][j])
}
}
}
我尝试过使用结构体,但在结构体上迭代时遇到了困难。我想避免使用map
,因为Go不允许我将其存储在const
中。
英文:
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\n", 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
得分: 1
根据我在你的伪代码中看到的内容和从评论中听到的内容,我会选择使用结构体的切片的切片:
所以我会定义一个结构体:
type subtask struct {
name string
kind int
}
其中name
将是你的api.example.com/stuff/
,kind
将是你的子任务类型:
我将对它们进行不同的处理(一些API需要不同的标头)
然后你的列表将如下所示:
list := [][]subtask{
[]subtask{subtask{"example1", 1}, subtask{"example2", 1}},
[]subtask{subtask{"example3", 1}, subtask{"example4", 2}},
}
这里是一个完整的工作示例 Playground。
英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论