I am trying to make a comparator, that takes either two string pointers, or two integer pointers and returns the result. any of pointer can be nil and i want true only when they have value and value is equal.
I tried with interface like
type T *interface{}
func compare(a T,b T) bool
because i had to check nil when cast *string to T, it is useless.
I am expecting to call function like
var a *string
var b *string
if compare(a, b){
// do something
}
or
var a *string
var b *string
if a.equal(b){
// do sth
}
Given that you are only working with two types, use type assertions to get the concrete pointer types and compare:
func compare(a interface{}, b interface{}) bool {
switch a := a.(type) {
case *string:
b, _ := b.(*string)
return a != nil && b != nil && *a == *b
case *int:
b, _ := b.(*int)
return a != nil && b != nil && *a == *b
default:
return false
}
}
Here are some examples of calling the function:
a := "hello"
b := "world"
c := "hello"
fmt.Println(compare(&a, nil))
fmt.Println(compare(nil, &a))
fmt.Println(compare(&a, &b))
fmt.Println(compare(&a, &a))
fmt.Println(compare(&a, &c))
Use the reflect API to compare all comparable types:
func compare(a interface{}, b interface{}) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
va := reflect.ValueOf(a)
vb := reflect.ValueOf(b)
if va.Type() != vb.Type() {
return false
}
if va.Kind() == reflect.Ptr {
if va.IsNil() || vb.IsNil() {
return false
}
va = va.Elem()
vb = vb.Elem()
}
if !va.Type().Comparable() {
return false
}
return va.Interface() == vb.Interface()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.