doufu9836 2017-10-09 05:24
浏览 15
已采纳

谁能提供您自己/标准的“克隆方法”惯例,以供我/我们参考?

I can't find a "clone" method convention in Golang, but it seems necessary to have one.

I only saw the built-in way *clonedObj = *obj, but it is too low-level, and can't handle (when-necessary) deep copy of case like struct { member *CompositionObj }

I doubt whether "func (obj ClassA) Clone() interface{}" prototype will work, because calling obj2 := obj.Clone() will "loose" the method set for ClassA, and need explicit code like obj2.(*ClassA) afterwards.

Please advice a working direction.

  • 写回答

2条回答 默认 最新

  • dongsheng1238 2017-10-12 03:38
    关注

    Ok, having some while no one else give me proper reference, I have found out some reference example how to clone in Go myself and want to share.

    (Only upvote me a few if this answer is useful to you. I'm not for earning votes. Welcome other better answers and comments)

    I found this protoype in package "github.com/jinzhu/gorm" (Database's ORM library) for reference:

    func (s *DB) clone() *DB {
        db := &DB{
            ...
        }
        ...
        return db
    }
    

    And similar pattern in package "golang.org/x/net/html/atom":

    func (n *Node) clone() *Node {
        m := &Node{
            Type:     n.Type,
            ...
        }
        ...
        return m
    }
    

    The above prototype is enough if the Clone()'s caller always know your object type when cloning. (and you need uppercase Clone() to make the method to be "public")

    However, if you want advanced feature that a variable may hold any object of similar base interface, here is my sample:

    func (t *T) Clone() YourBaseInterface
    

    Where YourBaseInterface is:

    type YourBaseInterface interface {
        Clone() YourBaseInterface
        OtherMethod1()
        ...
    }
    

    Or can merely use interface{} instead of YourBaseInterface in the return, and do a typecast like obj2 := obj.Clone().(*YourBaseType) after clone.

    CAUTION

    There is one drawback with this prototype. Becase Golang doesn't support this prototype as build-in, the Clone() method won't be called in some language's feature, e.g. when you copy(dest, src) a []YourTypeWithClone slice. Instead, it still do plain *elem2 = *elem1 struct copying. Solutions maybe either don't use those build-in, or you may flaw back to design the class struct members so that doing plain copy is enough for its copy purpose if possible.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等