【发布时间】:2021-10-09 15:20:21
【问题描述】:
我有一个函数需要接收类型,确定子类型,然后创建子类型的副本。我一直盯着这个功能,我觉得这可以简化,但我就是不知道如何让它发挥作用。代码如下:
func AddProp(prop prop, x, y int) []prop {
v := reflect.ValueOf(prop)
fmt.Printf("Prop type is %v", v.Type())
switch v.Type() {
case reflect.TypeOf(&Fence{}):
f := Fence{}
f.New(x, y)
props = append(props, &f)
case reflect.TypeOf(&Rock{}):
f := Rock{}
f.New(x, y)
props = append(props, &f)
}
return props
}
实际上比这长得多,还有更多案例。感谢您的观看!
编辑: 完全合理的问题 - 什么是道具?
type prop interface {
New(int, int)
}
第二次编辑: 我的结构如下所示:
type Prop struct {
fullImage image.Image
x, y int
}
type Fence struct {
Prop
horizontal bool
}
我为两者都定义了 New(x,y int)
func (p *Prop) New(x, y int)
func (p *Fence) New(x, y int)
我需要获取 Fence 结构并根据 Fence 而不是 Prop 调用 New
【问题讨论】:
-
什么是道具??
-
Go 中没有子类型。
-
一个名为
New的函数不返回任何内容...感觉不像 Go。你到底想做什么?
标签: go reflection dry