在范围功能中按地址引用

时间:2018-06-06 11:58:20

标签: go

我有一个OuterStruct结构定义如下。我正在使用该函数初始化OuterStruct -> InnerStruct中的Name and Var1setup1()Var1中的setup2()

setup2()中指定的值始终为nil,因为它是按值引用的。如何使用请参考我的地址?

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()
}

1 个答案:

答案 0 :(得分:2)

您无法通过地址访问,但您可以从range获取索引,并直接分配给切片:

    for i := range obj.MyData {
        obj.MyData[i].Var2 = callToPopulateValue()
    }

或者,您可以使用一段指针值:

type OuterStruct struct {
    opName   string
    MyDAta   []*InnerStruct
    LogDir   string
}

func (obj *OuterStruct) Setup2() {
    for _, innerObj := range obj.MyData {
        innerObj.Var2 = callToPopulateValue()
    }
}