duanou9758 2019-04-19 12:45
浏览 6

我如何创建通用功能来接收Go lang中的地图?

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?

  • 写回答

1条回答 默认 最新

  • douti9253 2019-04-19 12:57
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败