将接口类型的集合传递给函数 [英] Passing a collection of interface types to a function

查看:64
本文介绍了将接口类型的集合传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚在Go中使用接口的正确方法.我的函数需要对实现某种方法的项目进行映射.看起来像这样:

I'm having trouble figuring out the correct way to use interfaces in Go. My function needs to take a map of items that implement a certain method. It looks like this:

type foo interface {
    bar() string
}

func doSomething(items map[string]foo) {

}

我正在尝试使用实现 foo 接口的类型来调用此函数.

I'm trying to call this function with a type that implements the foo interface.

type baz struct { }

func (b baz) bar() string {
    return "hello"
}

items := map[string]baz{"a": baz{}}
doSomething(items)

但是出现以下错误:

cannot use items (type map[string]baz) as type map[string]foo in function argument

但是,当我这样做时,它工作正常:

However, it works fine when I do this:

items := map[string]foo{"a": baz{}}
doSomething(items)

但是我想针对不同的接口重用同一张地图.基本上,我索引了许多对象,然后将它们传递给需要实现不同接口以计算结果的各种函数.我想将地图传递给一个函数,将其作为 foo 的映射,将另一个函数传递给 foobar 的映射.

But I want to reuse this same map against different interfaces. Basically I'm indexing a lot of objects and then passing them to various functions that require different interfaces implemented to compute results. I want to pass the map to one function as a map of foo and another function as a map of foobar.

我尝试了各种类型断言和转换,但是似乎没有任何效果,所以我不确定是不是使用正确的语法还是完全错误地使用了.

I've tried various type assertions and conversions but nothing seems to work so I'm not sure if I'm just not using the correct syntax or just doing it completely wrong.

http://play.golang.org/p/8mMWCDG7vm 上进入游乐场.

推荐答案

这是一个非常常见的错误.

This is a fairly common mistake.

您正在混合这两种不同的类型:

You are mixing these two distinct types:

map[string]foo

map[string]baz

您不能简单地从一种地图类型转换为另一种地图类型. [] T 切片转换为 [] interface {} slices

You cannot simply convert from one map type to another. The same goes with converting []T slices to []interface{} slices, or converting chan T to chan interface{} (same question/answer but for channels).

map [string] foo 表示foo接口的映射,而不是在其中T实现foo接口的所有类型map [string] T.

map[string]foo means a map of foo interfaces, not all types map[string]T where T implements the foo interface.

您可以通过进行以下更改来解决它:

You can solve it by making this change:

items := map[string]foo{"a": baz{}}

游乐场:: http://play.golang.org/p/HxIVGSptwk

具有接口映射,您可以将不同的接口值类型转换为其他类型的接口.因此,地图可以重复使用.

Having a map of interfaces allows you to type cast the different interface values to other types of interfaces. So the map can be reused.

游乐场:: http://play.golang.org/p/20YMWmDjYT

但是,您应该有一个接口类型的映射,该接口类型是要存储在映射中的类型所实现的所有不同方法的交集.如果没有交叉点,则必须使用 interface {} 来确保可以存储任何类型.

But then you should have a map of an interface type that is the intersection of all the different methods implemented by the types to be stored in the map. If there is no intersection, then you will have to use interface{} to ensure that any type might be stored.

这篇关于将接口类型的集合传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆