go - 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.
解决方案
通过遍历 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
字段对切片进行排序并slice
在your_struct
.
如果切片不是很大,您可以创建额外的数据结构 -map[int]int
并将切片元素的索引保留在此映射中。但在这种情况下,您需要在修改其中之一时同步切片和地图的内容:
your_map := make(map[int]int)
if idx, ok := your_map[id]; ok {
// ...
}
推荐阅读
- servlets - ClassNotFoundException ===> com.sun.jersey.api.NotFoundException
- firebase - 在设定的时间后仅运行一次 cron 作业
- filter - 从以特定字符开头的多行单元格中提取行
- java - Java Socket 节点(代理)连接到尚未激活的节点
- javascript - 如果 URL 包含这些字词,则隐藏 div
- c# - 在没有 Active Directory 的情况下管理我的 Windows 应用程序逻辑中的用户
- python - Webapp2 Python set_cookie 不支持同站点cookie?
- python - 在我的案例中,如何使用附加字段设置多对多
- apache-spark - 为什么第一次和第二次执行spark sql查询的执行时间不同?
- python - Python attrs 类属性缓存延迟加载