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.