2017-03-02 09:13
浏览 70

在golang中返回self struct克隆(不反映)

there are two structs,
Foo has a Clone() method
Bar 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 {

func main() {
    t := &Bar{}
    c := t.Clone()
    fmt.Printf(`%T `, t)
    fmt.Printf(`%T `, c)


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


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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题