Skip to content

Instantly share code, notes, and snippets.

@sekky0905
Last active September 7, 2018 02:58
Show Gist options
  • Save sekky0905/0a5972cd62306ccecb3c39271597c01b to your computer and use it in GitHub Desktop.
Save sekky0905/0a5972cd62306ccecb3c39271597c01b to your computer and use it in GitHub Desktop.
GoのSliceの重複をMapを使って削除する ref: https://qiita.com/Sekky0905/items/ba2215981693b36e9982
package main
import "fmt"
func main() {
list := []string{"Go", "Java", "Python", "Go", "Ruby", "Go"}
m := make(map[string]struct{})
newList := make([]string, 0)
for _, element := range list {
// mapでは、第二引数にその値が入っているかどうかの真偽値が入っている
if _, ok := m[element]; !ok {
m[element] = struct{}{}
newList = append(newList, element)
}
}
fmt.Printf("mapの中身 %#v\n", m)
fmt.Printf("重複削除後 %#v\n", newList)
}
mapの中身 map[string]struct {}{"Go":struct {}{}, "Java":struct {}{}, "Python":struct {}{}, "Ruby":struct {}{}}
重複削除後 []string{"Go", "Java", "Python", "Ruby"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment