golang 判断更新和删除的数据
不在数据库中的数据则新增 [增量]
all := []string{"a", "b", "c", "d"}
update := []string{"a", "b", "c", "d", "f"}
add:= []string{"f"}
存在数据库中 不在请求的数据中的数据
all := []string{"a", "b", "c", "d"}
remove := []string{"f", "e"}
diff:= []string{"a", "b", "c", "d"}
请求示例
package main
import (
"fmt"
"strings"
)
func main() {
all := []string{"a", "b", "c", "d"}
currentMap := sliceToMap(all)
update := []string{"a", "b", "c", "d", "f"}
remove := []string{"f", "e"}
fmt.Println(updateStr(currentMap, update))
fmt.Println(removeStr(currentMap, remove))
}
func sliceToMap(current []string) map[string]struct{} {
resMap := make(map[string]struct{})
for _, s := range current {
resMap[s] = struct{}{}
}
return resMap
}
func updateStr(current map[string]struct{}, all []string) string {
var resStr []string
for _, s := range all {
if _, ok := current[s]; !ok {
resStr = append(resStr, s)
}
}
return strings.Join(resStr, ",")
}
func removeStr(current map[string]struct{}, all []string) string {
intersection := make(map[string]struct{})
for _, s := range all {
if _, ok := current[s]; ok {
intersection[s] = struct{}{}
}
}
var resStr []string
for s, _ := range current {
if _, ok := intersection[s]; !ok {
resStr = append(resStr, s)
}
}
return strings.Join(resStr, ",")
}
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/16393600.html