About clone an object (maps, slices, channels)

4,174 views
Skip to first unread message

atomaths

unread,
Dec 4, 2009, 6:42:58 PM12/4/09
to golang-nuts
Some types—maps, slices, and channels—have reference semantics.
How do I need to copy one object to another variable?

like Java's clone method...

Best regards.
Message has been deleted

Ian Lance Taylor

unread,
Dec 4, 2009, 9:43:52 PM12/4/09
to inspector_jouve, golang-nuts
atomaths <atom...@gmail.com> writes:

> Some types—maps, slices, and channels—have reference semantics.
> How do I need to copy one object to another variable?

There is no direct way to copy them. Code which clones an arbitary
map was posted on this list a day or two ago. Copying a slice
is more or less
dest := make([]T, len(source));
copy(dest, source);
(copy was added quite recently, though). Copying a channel doesn't
make a great deal of sense, though it's easy enough to make a new one.


inspector_jouve <kaush...@gmail.com> writes:

> look at reflect.DeepCopy

There is a reflect.DeepEqual, but there is no reflect.DeepCopy yet.
Though I'm sure we would look if somebody wrote one.

Ian

Jan Mercl

unread,
Apr 26, 2011, 8:06:50 AM4/26/11
to golan...@googlegroups.com
On Saturday, December 5, 2009 3:43:52 AM UTC+1, Ian Lance Taylor wrote:
There is a reflect.DeepEqual, but there is no reflect.DeepCopy yet.
Though I'm sure we would look if somebody wrote one.

Being in a need for DeepCopy I found this thread and taruti's take on the task:

If the above, posted in 2009, still holds, can it be possibly upgraded and incorporated into the current reflect package now? I will happily cooperate on this task if needed.

roger peppe

unread,
Apr 26, 2011, 8:18:52 AM4/26/11
to golan...@googlegroups.com
inspired by taruti's DeepCopy, i wrote a version some time ago that
also deals with recursive data structures and self-references.
those issues make DeepCopy somewhat harder than DeepEqual.

rog-go.googlecode.com/hg/exp/deepcopy

Jan Mercl

unread,
Apr 26, 2011, 8:31:52 AM4/26/11
to golan...@googlegroups.com
On Tuesday, April 26, 2011 2:18:52 PM UTC+2, rog wrote:
inspired by taruti's DeepCopy, i wrote a version some time ago that
also deals with recursive data structures and self-references.
those issues make DeepCopy somewhat harder than DeepEqual.

rog-go.googlecode.com/hg/exp/deepcopy

Nice, thank you. Let's see what are the dev team thoughts about it.
Reply all
Reply to author
Forward
0 new messages