首页 > 解决方案 > Optimal way to add or remove slice element in Go without broke elements order

问题描述

Assume I have []struct{} and I need to know whether an element with id = A exists in the slice. If exists, the element will be removed or moved to index 0 according to request in user input. So, how to find an element in golang slice in optimal way without check each element? Or, is using slice.contains(obj) enough? Then, if the element exists, I will do action according to request in user input. If the request is remove, I will remove it without broke the elements order. But if the request is add, I will move the element to index 0.

Note: The function will be often called. Thank you.

标签: go

解决方案


通过遍历 slice 来编写函数来查找元素并不难:

func contains(s []your_struct, e int) (bool, int) {
    for idx, a := range s {
        if a.id == e {
            return true, idx
        }
    }
    return false, -1
}

如果您要经常调用该函数,则按id字段对切片进行排序并sliceyour_struct.

如果切片不是很大,您可以创建额外的数据结构 -map[int]int并将切片元素的索引保留在此映射中。但在这种情况下,您需要在修改其中之一时同步切片和地图的内容:

your_map := make(map[int]int)
if idx, ok := your_map[id]; ok {
    // ...
}

推荐阅读