Using map as an element in struct


(Harshit Singhvi) #1

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


(Sean Killian) #2

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,
}

( Kvaz1r) #3

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: https://play.golang.org/p/QWMbhdY-Xa6


(Harshit Singhvi) #4

Thanks @GreyShatter.

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

Thanks again


(Harshit Singhvi) #5

Thanks @skillian for the resolution.