Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a field inside an anonymous struct

Tags:

go

Given this anonymous struct:

var myMap struct {
  list       map[string]string
  someStuff *some.Object
}

Can I initialize the list and someStuff in one declaration?

This doesn't work:

var myMap struct {
  list       map[string]string = make(map[string]string)
  someStuff *some.Object = &some.Object{}
}
like image 559
garbagecollector Avatar asked Nov 30 '22 17:11

garbagecollector


1 Answers

Here you go:

var myMap = struct {
  list map[string]string
  str string
}{
  list: map[string]string{"hello":"string"},
  str: "myString",
}

You can also do it this way:

var myMap = struct {
  list map[string]string
  str string
}{map[string]string{"hello":"string"}, "myString"}

And a working example: Go PlayGround.

So you declare your structure and then in curly braces you initiate it. (I learned it from this old go talk.)

like image 89
Salvador Dali Avatar answered Dec 04 '22 13:12

Salvador Dali