-4

I have the following code :

package main
import "fmt"

type config struct {
    user    string
    pass    string
    B       map[string]int 
}

func main() {
    conf := new(config)
    conf.user = "florence"
    conf.pass = "machine"
    //  trying to fill a map entry "x" where the value is 2 but the compiler throws an error
    conf.B["x"]=2

    fmt.Printf("%+v", conf)
}

which not compiling i am trying to add map where its key as string and value as numbers to struct as field but i am not able to access any help ?

alessiosavi
  • 2,753
  • 2
  • 19
  • 38
jsor
  • 97
  • 5
  • 5
    It compiles. What you have there is a panic, i.e. run-time error and not compile-time error, because the map is uninitialized. That means that to fix the run-time error you need to first initialize the B field and only then can you add values to it. – mkopriva Jan 28 '20 at 19:57
  • 3
    Please take the Tour of Go, which covers all the language basics and only takes a few minutes. This, for example, is covered here: https://tour.golang.org/moretypes/19 – Adrian Jan 28 '20 at 20:14

1 Answers1

0

Map types are reference types, like pointers or slices, and so the value of conf.B above is nil cause it doesn't point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don't do that. To initialize a map, use the built in make function:

conf.B = make(map[string]int)
alessiosavi
  • 2,753
  • 2
  • 19
  • 38