If I have a nested map variable like this inside a struct:
type someStruct struct {
nestedMap map[int]map[string]string
}
var ss = someStruct {
nestedMap: make(map[int]map[string]string),
}
This does not work and does a runtime error.
How do I initialize it?
Initializing nested Structuresstruct person { char name[20]; int age; char dob[10]; }; struct student { struct person info; int rollno; float marks[10]; } struct student student_1 = { {"Adam", 25, 1990}, 101, 90 }; The following program demonstrates how we can use nested structures.
Golang Create Nested MapWe start by setting the data type of the key (top-level map) and the type of the value. Since this is a nested map, the value of the top-level map is a map. The previous code creates a simple restaurant menu using nested maps. In the first map, we set the data type as an int.
A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. Go language allows nested structure.
You have to make the child maps as well.
func (s *someStruct) Set(i int, k, v string) {
child, ok := s.nestedMap[i]
if !ok {
child = map[string]string{}
s.nestedMap[i] = child
}
child[k] = v
}
playground
Initilize nested map like this:
temp := make(map[string]string,1)
temp ["name"]="Kube"
ss.nestedMap [2] = temp
fmt.Println(ss)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With