dqg17080 2015-03-12 09:20 采纳率: 0%
浏览 1534

如何在Golang的循环中删除结构数组的元素?

问题

我有一系列的结构:

type Config struct {
  Applications []Application
}

注意:config-是json.decode的结构。

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
}

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

  • 写回答

4条回答 默认 最新

  • dongpao1873 2015-03-12 09:29
    关注

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

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

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站