Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize a nested map inside a struct in Go?

Tags:

go

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?

like image 730
Alex Avatar asked Sep 26 '15 03:09

Alex


People also ask

How do you initialize a nested struct?

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.

How do I create a nested map in Golang?

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.

How do I create a struct inside a struct in Golang?

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.


2 Answers

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

like image 83
OneOfOne Avatar answered Oct 20 '22 21:10

OneOfOne


Initilize nested map like this:

temp := make(map[string]string,1)
temp ["name"]="Kube"
ss.nestedMap [2] = temp
fmt.Println(ss)
like image 26
Animesh Kumar Paul Avatar answered Oct 20 '22 22:10

Animesh Kumar Paul