how can i pass map data in to a general function (isExist) to check, the given value is exist or not passing map type may be map[int]int or map[string]string or any
func IsExist(text int, data map[interface{}]interface{}) bool {
for key, _ := range data {
if data[key] == text {
return true
}
}
return false
}
func main() {
var data = make(map[string]int)
//var data =map[interface {}]interface{} this case will working fine
data["a"] = 1
data["b"] = 2
fmt.Println(IsExist(2, data))
//throwing error that 'cannot use data (type map[string]int) as type map[interface {}]interface {} in argument to IsExist'
}
please let me know how can you generalize it?
Go's type system can't do that. map[string]int
and map[interface {}]interface{}
are distinct types. Besides, storage/representation of objects in memory depends on the type. A string has one memory layout. But the very same string, packaged as a interface{}
- totally different. For the same reasons you can't "cast" a []int
to a []interface{}
. You have to copy the elements into the new slice.
Same here. Either make your map a map[interface {}]interface{}
from the start, or copy all key-values pairs to one, prior to the call of the generic function.