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!
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"])
}