Using map as an element in struct

Hi Everyone,

package main

import (
	"fmt"
)

type person struct {
	firstName string
	lastName  string
	age       int
	mapper    map[string]int
}

type secretagent struct {
	p2   person
	kill bool
}

func main() {

	p1 := person{

		firstName: "Harshit",
		lastName:  "Singhvi",
		age:       30,
		mapper: {
			"James": 40, // Error on this line
			"Chima": 41,
		},
	}

	sa1 := secretagent{

		p2:   p1,
		kill: true,
	}

	fmt.Println("Printing p1", p1)
	fmt.Println(sa1.p2.age)

}

Can anyone tell me how to use map as a struct element in golang

1 Like

Hi, @Harshit_Singhvi, you can see an example of how to initialize maps from here: https://blog.golang.org/go-maps-in-action

The example on that page is:

commits := map[string]int{
    "rsc": 3711,
    "r":   2138,
    "gri": 1908,
    "adg": 912,
}
2 Likes

Well…as for me compiler message clear enough:

missing type in composite literal

so you just need specify a type, because Go is language with static typization.
Fix: Go Playground - The Go Programming Language

1 Like

Thanks @GreyShatter.

I am new to Go and your solution really helps!!!

Thanks again

1 Like

Thanks @skillian for the resolution.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.