Created
November 18, 2020 06:47
-
-
Save nanmu42/307ca9f5d8913690a59941e34d173310 to your computer and use it in GitHub Desktop.
Golang Remove Slice Duplicates
This file contains hidden or 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
// source: https://www.reddit.com/r/golang/comments/5ia523/idiomatic_way_to_remove_duplicates_in_a_slice/db6qa2e/ | |
func SliceUniqMap(s []int) []int { | |
seen := make(map[int]struct{}, len(s)) | |
j := 0 | |
for _, v := range s { | |
if _, ok := seen[v]; ok { | |
continue | |
} | |
seen[v] = struct{}{} | |
s[j] = v | |
j++ | |
} | |
return s[:j] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment