【发布时间】:2017-03-02 09:13:44
【问题描述】:
有两个结构,Foo 有一个Clone() 方法Bar 继承自Foo
package main
import "fmt"
type IF interface {
Clone() IF
}
type Foo struct {
i int
}
func (this *Foo) Clone() IF {
c := *this
return &c
}
type Bar struct {
Foo
}
func main() {
t := &Bar{}
c := t.Clone()
fmt.Printf(`%T `, t)
fmt.Printf(`%T `, c)
}
https://play.golang.org/p/pFn348aydW
输出是
*main.Bar *main.Foo
但我想克隆一个Bar,而不是Foo
我必须添加Bar.Clone() 与Foo.Clone() 完全相同
func (this *Bar) Clone() IF {
c := *this
return &c
}
https://play.golang.org/p/J6jT_0f1WW
现在输出是我想要的
*main.Bar *main.Bar
如果我会写很多像Bar 这样的结构,我不会写很多Clone(),我能做什么?
最好不要使用反射
【问题讨论】:
标签: go