Created
November 1, 2013 16:46
-
-
Save timbogit/7268231 to your computer and use it in GitHub Desktop.
Working variadic function with interfaces as arguments
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" | |
) | |
type TestStruct struct { | |
int | |
string | |
} | |
func UniqueOf(slice ...interface{}) []interface{} { | |
seen := make(map[interface{}]int, len(slice)) | |
result := make([]interface{}, len(slice)) | |
resultIndex := 0 | |
for _, val := range slice { | |
if _, ok := seen[val]; !ok { | |
result[resultIndex] = val | |
resultIndex++ | |
} | |
seen[val] = 1 | |
} | |
return result[:resultIndex] | |
} | |
func main() { | |
fmt.Printf("%v is unique\n", | |
UniqueOf("hello", 15, "hello", 15, 16, 42, | |
TestStruct{1, "hello"}, TestStruct{2, "hi"}, TestStruct{2, "hi"})) | |
} | |
/* Output | |
tim-schmelmers-macbook:go tim$ go run go_challenge_works.go | |
[hello 15 16 42 {1 hello} {2 hi}] is unique | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment