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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作