I'm sure there's a good explanation for this, but I've not been able to find it. Can anyone help me understand what is happening the following code example?
package main
import (
"fmt"
)
type work struct {
data map[string]string
}
func (w work) doSome() {
w.data = make(map[string]string)
w.data["k1"] = "v1"
}
func main() {
work := work{}
work.doSome()
if work.data == nil {
fmt.Println("data is nil")
} else {
fmt.Println("data is", work.data)
}
}
This prints out data is nil
, which is not what I expected. If I rework this to be a pointer type (i.e. *work
) for doSome
method , it initializes the struct's variable. I'd like to understand why these are different. I assume it's something to do with map
being a pointer, of sorts, but haven't been able to find a good reference to explain this.
Playground link - https://play.golang.org/p/lTN11TRkRNj