duandingqi9442 2017-12-27 22:59
浏览 23
已采纳

可以采用多种类型的功能

I'm trying to create a helper function which will take a map with string keys and return a slice of the map keys.

The problem is that I want the function to not care about the type of the map values.

For example:

stringStringMap := map[string]string{
    "one": "first",
    "two": "second"
}

mapKeys(stringStringMap) // ["one", "two"]

stringIntMap := map[string]int{
    "one": 1,
    "two": 2,
}

mapKeys(strinIntMap) // ["one", "two"]

It seems that the only way around this problem is to create two similar helpers. Something like this:

func mapKeys(m map[string]string) []string {
    ...
}

func mapKeys2(m map[string]int) []string {
    ...
}

But this seems ugly. Is this helper function I'm trying to create possible?If not, is there a good convention I should follow when writing this?

  • 写回答

3条回答 默认 最新

  • dtch60248 2017-12-28 10:05
    关注

    There is a third option not mentioned yet, and that is to use a type switch. This may be a good option if you know that you'll be passing a manageable number of types to the function. It would work like this:

    func Keys(m interface{}) ([]string, error) {
        switch t := m.(type) {
        case map[string]string:
            keys := make([]string, 0, len(t))
            for key := range t {
                keys = append(keys, key)
            }
            return keys, nil
        case map[string]int:
            keys := make([]string, 0, len(t))
            for key := range t {
                keys = append(keys, key)
            }
            return keys, nil
        default:
            return nil, fmt.Errorf("unknown map type: %T", m)
        }
    }
    

    This still gives you a bunch of seemingly duplicate code, but at least it's all behind a single function name, and it's more efficient than reflection.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了