简体   繁体   English

go 中的递归 function 不存储更改

[英]Recursive function in go is not storing changes

//Recursively set ExternalID for all Parts, PartUse, Components in Component struct
func (svc *ProductManagementClient) setExternalID(input *[]Component) *[]Component {
    for _, component := range *input {
        if component.Components != nil {
            component.Components = svc.setExternalID(component.Components)
        }
        component.PartUse.ExternalID = component.PartUse.ID
        component.Part.ExternalID = component.Part.ID
        for _, occurrence := range component.Occurrences {
            occurrence.ExternalID = occurrence.ID
        }
        component.ExternalID = "PartID:" + component.Part.ID + ",PartUseID:" + component.PartUse.ID
        zap.S().Debug("ExternalID for component:", component.ExternalID)
    }
    return input
}

In this function, I'm trying to set the ExternalID field for these structs, and I'm calling it from another function.在这个 function 中,我试图为这些结构设置 ExternalID 字段,并且我从另一个 function 调用它。 The code snippet for that is below:代码片段如下:

// Set externalID for each Part, PartUse and Component
for _, component := range retBOM.Components {
    component.Components = svc.setExternalID(component.Components)
}

The changes aren't being persisted, and I'm unable to tell why.更改没有被保留,我无法说出原因。 When I look at the result, the ExternalID fields are still coming up empty.当我查看结果时,ExternalID 字段仍然为空。 I'm writing a recursive function because the Component field is nested.我正在编写递归 function 因为 Component 字段是嵌套的。 How can I fix this?我怎样才能解决这个问题?

I tried to pass by reference but apparently that's not allowed in Golang.我试图通过引用传递,但显然这在 Golang 中是不允许的。

Its because in cycle youre modifying copy of Component.这是因为在循环中您正在修改组件的副本 at the end of iteration you must replace it like在迭代结束时,您必须像这样替换它

for i, component := range *input {
    if component.Components != nil {
        component.Components = svc.setExternalID(component.Components)
    }
    component.PartUse.ExternalID = component.PartUse.ID
    component.Part.ExternalID = component.Part.ID
    for _, occurrence := range component.Occurrences {
        occurrence.ExternalID = occurrence.ID
    }
    component.ExternalID = "PartID:" + component.Part.ID + ",PartUseID:" + component.PartUse.ID
    zap.S().Debug("ExternalID for component:", component.ExternalID)
    // replace current state by new one
    *input[i] = component
}

or use []*Component / *[]*Component instead of *[]Component或使用 []*Component / *[]*Component 而不是 *[]Component

A closely related question here一个密切相关的问题here

But as many pointed out, you are passing the copy of the component but address of the slice.但正如许多人指出的那样,您传递的是组件的副本,而是切片的地址。

so the fastest way to handle this is to use []*Component which in layman means a slice of pointer components所以处理这个问题的最快方法是使用[]*Component在外行的意思是指针组件的切片

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM