This question already has an answer here:
I am new to Golang. I have this simple code, that I can't get to work; the problem is that after call the method LoadGroups
, the "main" function doesn't see the changes:
package main
import "fmt"
type Group struct {
Name string
}
type Configuration struct {
Groups []Group
}
func NewConfiguration() (error, *Configuration) {
conf := Configuration{}
conf.LoadGroups()
fmt.Print("Final number of groups: ", len(conf.Groups))
return nil, &conf
}
func (conf Configuration) LoadGroups() {
for i := 0; i < 5; i++ {
conf.Groups = append(conf.Groups, Group{Name: "Group " + string(i)})
fmt.Println("Current number of groups: ", len(conf.Groups))
}
}
func main() {
NewConfiguration()
}
Playground: https://play.golang.org/p/VyneKpjdA-
</div>
You are modifying a copy of the Configuration, not the Configuration itself.
The method LoadGroups
should take a pointer to a Configuration instead:
package main
import "fmt"
type Group struct {
Name string
}
type Configuration struct {
Groups []Group
}
func NewConfiguration() (error, *Configuration) {
conf := &Configuration{}
conf.LoadGroups()
fmt.Print("Final number of groups: ", len(conf.Groups))
return nil, conf
}
func (conf *Configuration) LoadGroups() {
for i := 0; i < 5; i++ {
conf.Groups = append(conf.Groups, Group{Name: "Group " + string(i)})
fmt.Println("Current number of groups: ", len(conf.Groups))
}
}
func main() {
NewConfiguration()
}
The LoadGroups
method must be a receiver of *Configuration
, instead of Configuration
. Right now the method LoadGroup
is being executed on a fresh copy of Configuration
each time is called, therefore its changes are not reflected in the original caller. By making it of type *Configuration
, all calls to the method LoadGroups
sharing the same pointer change the same Configuration
instance.