replay
replay

Reputation: 3819

Function that takes map and only cares about key type

I have two maps, both of them are keyed by strings, but the values are of two different custom types.

map[string]type1
map[string]type2

Now I want to write a function which can take an argument of either of these two types, because that function only looks at the keys and doesn't care about the values at all. So I think it should look like this:

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

But that doesn't work due to:

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

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

Can I make that work somehow?

Upvotes: 0

Views: 204

Answers (2)

jmaloney
jmaloney

Reputation: 12320

A solution using an interface. This example may seem a bit overkill and it may be better to in your case (I'm not sure, not enough details in your example) to just use a couple of for loops.

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())
}

Playground example

Upvotes: 0

Adrian
Adrian

Reputation: 46602

The only polymorphism in Go is interfaces. The only alternatives to that are reflection, duplication, or rethinking the broader design so that you don't need to do what you're trying to do here.

If the last option isn't a possibility, personally I would recommend duplication, since it's a whole four lines of code.

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

A big complicated generic helper seems kind of unnecessary.

Upvotes: 5

Related Questions