如何在golang的循环中删除struct数组的元素

如何在golang的循环中删除struct数组的元素

本文介绍了如何在golang的循环中删除struct数组的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我有结构数组:

type Config struct {
  Applications []Application
}

注意:配置 - 是 json.Decode 的结构.

Note: Config - is a struct for json.Decode.

config = new(Config)
_ = decoder.Decode(&config)

在循环中,我通过键删除了一些条件和元素.

In loop I have some condition and element deletion by key.

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
}

但我总是有超出范围"的错误.从结构数组中逐键删除元素的最佳方法是什么?

But always I have "out of range" error. What is the best way to delete element by key from array of structs?

推荐答案

引用自 Slice Tricks 页面删除索引 i 处的元素:

Quoting from the Slice Tricks page deleting the element at index i:

a = append(a[:i], a[i+1:]...)
// or
a = a[:i+copy(a[i:], a[i+1:])]

请注意,如果您打算从当前循环的切片中删除元素,则可能会导致问题.如果您删除的元素是当前元素(或已经循环的前一个元素),它会这样做,因为删除后所有后续元素都被移位,但是 range 循环不知道这一点,并且仍然会增加索引并跳过一个元素.

Note that if you plan to delete elements from the slice you're currently looping over, that may cause problems. And it does if the element you remove is the current one (or a previous element already looped over) because after the deletion all subsequent elements are shifted, but the range loop does not know about this and will still increment the index and you skip one element.

您可以通过使用向下循环来避免这种情况:

You can avoid this by using a downward loop:

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:]...)
    }
}

这篇关于如何在golang的循环中删除struct数组的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 19:32