I have a OuterStruct
structure defined as given below. I am using the function to initialize the OuterStruct -> InnerStruct
values Name and Var1
in setup1()
and Var1
in setup2()
.
The value assigned in setup2() is nil
always because it is referring it by value. How to use refer my address here ?
type InnerStruct struct {
Name string
Var1 *api.Var1
Var2 *ap1.Var2
}
type OuterStruct struct {
opName string
MyData []InnerStruct
LogDir string
}
func (obj *OuterStruct) Setup2() {
for _, innerObj := range obj.InnerStruct { // Here is the prob becuase of using refer by value
innerObj.Var2 = callToPopulateValue()
}
}
func Setup1() {
innerStructList := []InnerStruct
myStruct := InnerStruct{}
myStruct.Name = "name1"
myStruct.Var1 = callToPopulateValue()
innerStructList = append(innerStructList, myStruct)
finalStruct = &OuterStruct {
opName: "structName",
MyData: innerStructList,
LogDir: "/path/for/my/logs",
}
finalStruct.Setup2()
}
You can't access by address, but you can get the index from range
instead, and assign to the slice directly:
for i := range obj.MyData {
obj.MyData[i].Var2 = callToPopulateValue()
}
Alternately, you can just use a slice of pointer values:
type OuterStruct struct {
opName string
MyDAta []*InnerStruct
LogDir string
}
func (obj *OuterStruct) Setup2() {
for _, innerObj := range obj.MyData {
innerObj.Var2 = callToPopulateValue()
}
}