Created
March 17, 2022 11:21
-
-
Save sw360cab/06849054d8bcff35476b6d9b95b75b2b to your computer and use it in GitHub Desktop.
using reflection to create a generic lookup method in Go
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" | |
"reflect" | |
) | |
// Check if item is i an array for any type using reflection | |
func containsAny(items interface{}, value interface{}) bool { | |
itemsValue := reflect.ValueOf(items) | |
if itemsValue.Kind() != reflect.Slice { | |
return false | |
} | |
for i := 0; i < itemsValue.Len(); i++ { | |
if reflect.DeepEqual(itemsValue.Index(i).Interface(), value) { // value, short for -> reflect.Value(value).Interface() | |
fmt.Printf("%s and %s \n", itemsValue.Index(i).Type().String(), reflect.ValueOf(value).Type().String()) | |
fmt.Printf("%v and %v \n", itemsValue.Index(i), reflect.ValueOf(value)) | |
return true | |
} | |
} | |
return false | |
} | |
// test | |
type Sex struct { | |
aname string | |
isMale bool | |
} | |
type Superman struct { | |
values []int64 | |
} | |
type Metric struct { | |
Name string | |
val int | |
Peolple []string | |
mens []Superman | |
Sex | |
} | |
// main | |
func main() { | |
var k int64 | |
k = 3 | |
superman := Superman{ | |
values: []int64{1, 2, 3}, | |
} | |
fmt.Println(containsAny([]int{3, 4, 5, 6}, 4)) | |
fmt.Println(containsAny([]int64{3, 4, 5, 6}, k)) | |
aMetric := &Metric{ | |
Name: "Pino", | |
val: 100, | |
Peolple: []string{"tizio", "caio"}, | |
mens: []Superman{superman}, | |
Sex: Sex{ | |
aname: "alborg", | |
isMale: true}, | |
} | |
fmt.Println(containsAny([]*Metric{aMetric, | |
{ | |
Name: "Balo", | |
val: 111, | |
Peolple: []string{"tizio", "caio"}, | |
Sex: Sex{ | |
aname: "alborg", | |
isMale: true}, | |
}, | |
}, aMetric)) | |
fmt.Println(containsAny([]Metric{*aMetric, | |
{ | |
Name: "Balo", | |
val: 111, | |
Peolple: []string{"tizio", "caio"}, | |
Sex: Sex{ | |
aname: "alborg", | |
isMale: true}, | |
}, | |
}, Metric{ | |
Name: "Pino", | |
val: 100, | |
Peolple: []string{"tizio", "caio"}, | |
mens: []Superman{superman}, | |
Sex: Sex{ | |
aname: "alborg", | |
isMale: true}, | |
})) | |
fmt.Println(containsAny([]*Metric{aMetric, | |
{ | |
Name: "Balo", | |
val: 111, | |
Peolple: []string{"tizio", "caio"}, | |
Sex: Sex{ | |
aname: "alborg", | |
isMale: true}, | |
}, | |
}, &Metric{ | |
val: 22, | |
})) // false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment