我有一個地圖數組,如果它存在,我想從中刪除一個元素,這由它的“鍵”確定。怎么做?我希望它不慢。保持順序并不重要。myMaps = []map[string]interface{} { map[string]interface{} {"key": "aaa", "key2": 222, "key3": "aafdsafd"}, map[string]interface{} {"key": "key_to_delete", "key2": 366, "key3": "333aafdsafd"}, map[string]interface{} {"key": "cccc", "key2": 467, "key3": "jhgfjhg"}, }for _, x := range myMaps { if x["key"] == "key_to_delete" { //delete this element as a) key of the map b) the map-element as an element of the array; How? }}delete(...)功能:當迭代一個數組時,它的副本是在循環體中傳遞的。不?那么如何delete(...)從真實數組中刪除一個元素?更新:我需要知道如何刪除 2 類實體,就我而言:數組的一個元素 - 一張地圖地圖的一個元素,具有特定的鍵不使用第三方庫。
1 回答

繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
如果要從地圖中刪除密鑰:
for _, x := range myMaps {
if x["key"] == "key_to_delete" {
delete(x, "key")
}
}
如果你想要的是從數組中刪除它變得復雜的地圖,如果要保留當前地圖,你最好創建第二個數組并插入其中:
myFilteredMaps := make([]map[string]interface{}, 0, len(myMaps))
for _, x := range myMaps {
if x["key"] != "key_to_delete" {
myFilteredMaps = append(myFilteredMaps, x)
}
}
myMaps = myFilteredMaps
只要len(myMaps)不是太大,這兩者都非??欤瑑烧叨季哂邢鄬τ谠撻L度的線性運行時間。
- 1 回答
- 0 關注
- 102 瀏覽
添加回答
舉報
0/150
提交
取消