Home > OS >  Recursive function in go is not storing changes
Recursive function in go is not storing changes

Time:08-18

//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. 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. I'm writing a recursive function because the Component field is nested. How can I fix this?

I tried to pass by reference but apparently that's not allowed in Golang.

CodePudding user response:

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

CodePudding user response:

A closely related question 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

  • Related