其他分享
首页 > 其他分享> > go 循环切片得到重复移除成别名

go 循环切片得到重复移除成别名

作者:互联网

import "fmt"
func removeDuplicateElement(addrs []string) []string {
result := make([]string, 0, len(addrs))
temp := map[string]struct{}{}
idx := 0
for _, item := range addrs {
if _, ok := temp[item]; !ok {
temp[item] = struct{}{}
result = append(result, item)
} else {
idx++
item += fmt.Sprintf("(%v)", idx)
result = append(result, item)
}
}
return result
}


func main() {
fmt.Println(removeDuplicateElement([]string{"fsdf","fdsfsdf","fsdf"}))



}



[fsdf fdsfsdf fsdf(1)]
func removeDuplicateElement(addrs []string) []string {
  result := make([]string, 0, len(addrs))
  temp := map[string]struct{}{}
  idx := 0
  for _, item := range addrs {
  if _, ok := temp[item]; !ok {
  temp[item] = struct{}{}
  result = append(result, item)
  } else {
  idx++
  item += fmt.Sprintf("(%v)", idx)
  result = append(result, item)
  }
  }
  return result
  }
 

标签:string,idx,temp,别名,item,result,移除,go,addrs
来源: https://www.cnblogs.com/cheyunhua/p/15937011.html