【发布时间】:2019-01-12 15:22:27
【问题描述】:
我尝试使用对象的类型在接口切片中查找对象。我目前的解决方案如下:
package main
import (
"errors"
"fmt"
)
type Entity struct {
children []Childable
}
func (e *Entity) ChildByInterface(l interface{}) (Childable, error) {
for _, c := range e.children {
if fmt.Sprintf("%T", c) == fmt.Sprintf("%T", l) {
return c, nil
}
}
return nil, errors.New("child doesn't exist")
}
type Childable interface {
GetName() string
}
func main() {
ent := &Entity{
[]Childable{
&Apple{name: "Appy"},
&Orange{name: "Orry"},
// more types can by introduced based on build tags
},
}
appy, err := ent.ChildByInterface(&Apple{})
if err != nil {
fmt.Println(err)
} else {
appy.(*Apple).IsRed()
fmt.Printf("%+v", appy)
}
}
type Apple struct {
name string
red bool
}
func (a *Apple) GetName() string {
return a.name
}
func (a *Apple) IsRed() {
a.red = true
}
type Orange struct {
name string
yellow bool
}
func (o *Orange) GetName() string {
return o.name
}
func (o *Orange) IsYellow() {
o.yellow = true
}
https://play.golang.org/p/FmkWILBqqA-
可以使用构建标签注入更多 Childable 类型(Apple、Orange 等)。因此,为了保证查找类型的安全并避免错误,我将interface{} 传递给查找函数。 Childable 接口还确保新注入的类型实现正确的功能。
这就是事情开始变得混乱的地方。目前我正在对接口的类型和 Childable 对象的类型进行字符串比较,以查看它们是否匹配:
fmt.Sprintf("%T", c) == fmt.Sprintf("%T", l)
那我还是只能返回 Childable 接口。所以我必须使用类型断言来获得正确的类型:appy.(*Apple)
为了让子项具有正确的类型而进行的锅炉电镀变得非常乏味,而字符串比较以找到匹配项对性能产生了重大影响。我可以使用什么更好的解决方案来匹配两个接口以避免性能冲击?
【问题讨论】:
-
接口的使用方式是需要键入断言值以获取基础类型。你想达到什么目标?
-
在返回值上应用显式类型断言是这样做的方法。当您依赖运行时信息来执行实现时,您将始终受到“性能”影响。这可能与您正在寻找的类型相等测试 github.com/mh-cbon/service-finder/blob/master/… 接近
-
使用
Is("red")之类的东西并在两个对象上调用Is函数不是更好吗? -
@danicheeta 我刚刚添加了 IsRed 和 IsYellow 函数来表明这两个结构应该能够具有不同的方法(因此需要类型断言)。根据您的建议,我意识到它们的效率很低。
标签: go interface type-assertion