1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package main
import (
"fmt"
)
func main() {
users := []map[string]string{
{"id": "1", "name": "test1", "contact": "11234", "address": "Guangdong"},
{"id": "2", "name": "test2", "contact": "21234", "address": "Shanghai"},
{"id": "3", "name": "test3", "contact": "31234", "address": "Hangzhou"},
{"id": "4", "name": "test4", "contact": "41234", "address": "Shenzhen"},
}
fmt.Println(users)
id := "1"
// 方法1:
// 把不需要删除 => 定义新的切片 => users,使用 append 进行重新组合
// tempUsers := []map[string]string{}
tmpUsers := make([]map[string]string, 0, len(users)-1) // 定义一个临时的 map 函数
for _, user := range users {
if user["id"] != id { //这里把不等于的 id 一个一个写入 tmpUsers,
// fmt.Println(user)
tmpUsers = append(tmpUsers, user)
}
// users = tmpUsers
}
fmt.Println(tmpUsers)
}
|