Last active
September 7, 2018 02:58
-
-
Save sekky0905/0a5972cd62306ccecb3c39271597c01b to your computer and use it in GitHub Desktop.
GoのSliceの重複をMapを使って削除する ref: https://qiita.com/Sekky0905/items/ba2215981693b36e9982
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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