场景
自定义结构体切片,去除切片中的重复元素(所有值完全相同)
代码
// 自定义struct去重
type AssetAppIntranets struct {ID string `json:"id,omitempty"`AppID string `json:"app_id,omitempty"`IP string `json:"ip,omitempty"`Port int `json:"port,omitempty"`Domain string `json:"domain,omitempty"`
}// 切片去重函数
func RemoveDuplicates(s []AssetAppIntranets) []AssetAppIntranets {m := make(map[AssetAppIntranets]bool)result := []AssetAppIntranets{}for _, v := range s {if _, ok := m[v]; !ok {m[v] = trueresult = append(result, v)}}return result
}
// 字符串切片、整型切片去重
func RemoveDuplicate[T string | int | int64 | struct{}](slice []T) []T {result := make([]T, 0)temp := map[T]struct{}{}for _, item := range slice {if _, ok := temp[item]; !ok {temp[item] = struct{}{}result = append(result, item)}}return result
}
解读
使用映射m检查元素v是否存在。如果v不在映射中(即第一次出现),则返回的布尔值指示该键是否存在于映射中。如果布尔值为true,则表示该键不存在于映射中;如果为false,则表示该键已存在。
如果元素不在映射中,我们将它添加到映射中并添加到结果切片中。