【go】结构体切片去重

场景

自定义结构体切片,去除切片中的重复元素(所有值完全相同)

代码

// 定义的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] = true
			result = append(result, v)
		}
	}
	return result
}

解读

使用映射m检查元素v是否存在。如果v不在映射中(即第一次出现),则返回的布尔值指示该键是否存在于映射中。如果布尔值为true,则表示该键不存在于映射中;如果为false,则表示该键已存在。
如果元素不在映射中,我们将它添加到映射中并添加到结果切片中。

你可能感兴趣的:(go,golang,后端)