可以将重复的代码抽象成一个单独的函数,然后在需要使用的地方进行调用。下面是一个示例代码:
func removeDuplicates(slc []string) []string {
keys := make(map[string]bool)
result := []string{}
for _, entry := range slc {
if _, value := keys[entry]; !value {
keys[entry] = true
result = append(result, entry)
}
}
return result
}
func main() {
// 去重字符串切片
a := []string{"apple", "orange", "banana", "apple", "grape", "orange", "banana", "banana"}
b := removeDuplicates(a)
fmt.Println(b)
// 去重字符串映射
m := map[string]bool{
"apple": true,
"orange": true,
"banana": true,
"grape": true,
}
c := []string{}
for key := range m {
c = append(c, key)
}
d := removeDuplicates(c)
fmt.Println(d)
}
在上面的代码中,我们定义了一个removeDuplicates
函数,用于去重字符串切片和映射。我们可以通过调用该函数来去重切片和映射中的数据,避免在代码中重复编写相同的去重逻辑。
下一篇:避免在子类中进行类型转换