获取地图并且只关心键类型的函数

问题描述 投票:0回答:2

我有两张地图,它们都由

strings
键控,但值是两种不同的自定义类型。

map[string]type1
map[string]type2

现在我想编写一个可以接受这两种类型的参数的函数,因为该函数只查看键,根本不关心值。所以我认为它应该看起来像这样:

func takeTheMap(argument map[string]interface{}) {
...

但这不起作用,因为:

cannot use myVariable (type map[string]customType) as type map[string]interface {} in argument to takeTheMap

https://play.golang.org/p/4Xkhi4HekO5

我能以某种方式让它发挥作用吗?

dictionary go generics
2个回答
5
投票

Go 中唯一的多态性是接口。唯一的选择是反思、重复或重新思考更广泛的设计,这样你就不需要做你在这里想做的事情。

如果最后一个选项不可行,我个人建议重复,因为它是整整四行代码。

keys := make([]string, 0, len(myMap))
for key,_ := range myMap {
    keys = append(keys,key)
}

一个大而复杂的通用助手似乎没有必要。


0
投票

使用接口的解决方案。这个例子可能看起来有点矫枉过正,在你的情况下(我不确定,你的例子中没有足够的细节)最好只使用几个

for
循环。

package main

import (
    "fmt"
)

type foo bool
type bar string

type mapOne map[string]foo
type mapTwo map[string]bar

func (m mapOne) Keys() []string {
    s := []string{}
    for k := range m {
        s = append(s, k)
    }
    return s
}

func (m mapTwo) Keys() []string {
    s := []string{}
    for k := range m {
        s = append(s, k)
    }
    return s
}

type ToKeys interface {
    Keys() []string
}

func main() {
    m1 := mapOne{"one": true, "two": false}
    m2 := mapTwo{"three": "foo", "four": "bar"}

    doSomething(m1)
    doSomething(m2)
}

func doSomething(m ToKeys) {
    fmt.Println(m.Keys())
}

游乐场示例

© www.soinside.com 2019 - 2024. All rights reserved.