Efficient Deletion of Elements from Struct Arrays in Golang
While working with arrays of structs, it's often necessary to remove specific elements based on conditions. The following code demonstrates an issue encountered when attempting to delete an element at index 'i' from an array called 'config.Applications':
type Config struct { Applications []Application } config = new(Config) _ = decoder.Decode(&config) for i, application := range config.Applications { if i == 1 { config.Applications = _removeApplication(i, config.Applications) } } func _removeApplication(i int, list []Application) []Application { if i < len(list)-1 { list = append(list[:i], list[i+1:]...) } else { log.Print(list[i].Name) list = list[:i] } return list }
This code results in an "out of range" error because the for loop still tries to access the deleted element at index 'i'. To address this issue, it's recommended to use one of the following efficient deletion techniques:
list = append(list[:i], list[i+1:]...)
list = list[:i]
list = list[:i+copy(list[i:], list[i+1:])]
Note that when deleting elements from an array you're currently looping over, it's best to use a downward loop to avoid potential index issues:
for i := len(config.Applications) - 1; i >= 0; i-- { application := config.Applications[i] // Condition to decide if current element has to be deleted: if haveToDelete { config.Applications = append(config.Applications[:i], config.Applications[i+1:]...) } }
The above is the detailed content of How to Efficiently Delete Elements from Struct Arrays in Go?. For more information, please follow other related articles on the PHP Chinese website!