How to deep copy objects in the Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Deep replication can be reflect done based on the reflection mechanism of the package, but it is tedious to write all the way back.

The simplest approach is to implement deep replication of objects based on serialization and deserialization:

Func deepcopy (DST, src interface{})Error{varbuf bytes. Bufferif Err: = Gob. Newencoder (&BUF).Encode(SRC);Err! = Nil {return Err}returnGob. Newdecoder (bytes. Newbuffer (BUF. Bytes ())).Decode(DST)}

The simple combination of gob and bytes.buffer is done. Of course, the bottom of Gob is also based on reflect packages.

Serialize in memory, deserialize object entities to complete deep copies of object entities this is the idiom for most languages to implement deep copies of objects.

Add: Golang is completely by value, so the normal assignment is a value copy, of course, if the type inside a nested pointer, is also a copy of the pointer value, there will be two types of variables within the internal part is shared.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.