Go中的函数参数可以是一种满足它所嵌入的每种类型的类型吗?

时间:2017-04-26 01:46:43

标签: go

Go中是否可以有一个满足多种类型的函数参数?我知道你可以使用接口传递各种类型,但让我举个例子。

说我有以下三种类型:

type thing struct {
    name string
}

type barThing struct {
    thing
    barAttr string
}

type fooThing struct {
    thing
    fooAttr int
}

我想要一个函数,以便我可以传入map[string]<anyOfThoseTypes>并将每个地图项的键添加到名称字段。类似的东西:

func copyKeysIntoStruct(m map[string]thing) {
    for k, v := range m {
        v.name = k
        m[k] = v
    }
}

func main() {
    bars := map[string]barThing{
        "b1": {thing: thing{name: "overwrite"}},
        "b2": {thing: thing{}},
    }
    foos := map[string]fooThing{
        "f1": {thing: thing{}},
        "f2": {thing: thing{name: "goingaway"}},
    }
    bars = copyKeysIntoStruct(bars)
    fmt.Println(bars)
    foos = copyKeysIntoStruct(foos)
    fmt.Println(foos)
}

然而,在这里我得到cannot use bars (type map[string]barThing) as type map[string]thing in argument to copyKeysIntoStruct,这是有道理的。但是,我不想为嵌入了thing的每种类型编写相同的函数。

另一种可能性是将m map[string]interface{}作为参数并使用类型切换和断言来获得正确的行为,但这似乎也是一个NOGO。

总之,我希望得到如下输入:

    bars := map[string]barThing{
        "b1": {thing: thing{name: "overwrite"}},
        "b2": {thing: thing{}},
    }
    foos := map[string]fooThing{
        "f1": {thing: thing{}},
        "f2": {thing: thing{name: "goingaway"}},
    }

和输出如:

    bars := map[string]barThing{
        "b1": {thing: thing{name: "b1"}},
        "b2": {thing: thing{name: "b2"}},
    }
    foos := map[string]fooThing{
        "f1": {thing: thing{name: "f1"}},
        "f2": {thing: thing{name: "f2"}},
    }

0 个答案:

没有答案