如何删除结构数组元素在golang循环 [英] How to remove element of struct array in loop in golang

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

问题描述

问题

我有结构的数组:

type Config struct {
  Applications []Application
}

注:配置 - 是json.De code进行结构

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?

推荐答案

切片技巧报价页面删除在指数的元素 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:])]

请注意,如果您打算删除切片您当前遍历元素,这可能会导致问题。而它,如果你删除的元素是因为删除后,所有后续元素都转移了当前(或已循环超过previous元素),但范围循环不知道这一点,仍然会递增指标,你跳过一个元素。

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循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆