there are two structs,Foo
has a Clone()
methodBar
is inherit from 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
output is
*main.Bar *main.Foo
but I want clone a Bar
, not Foo
I must add Bar.Clone()
exactly the same as Foo.Clone()
func (this *Bar) Clone() IF {
c := *this
return &c
}
https://play.golang.org/p/J6jT_0f1WW
Now the output is what I want
*main.Bar *main.Bar
If I will write lots of struct like Bar
, I won't write lots of Clone()
, what I can do ?
It is best not to use reflect