Copying an Object in Golang Is That Easy??

I've worked in many languages over the years.  Java and C# have been much of my time.  When I needed to create a new instance of an object in C#, I would need to do something like this:

Foo foo = new Foo{
prop1 = "thing1"
prop2 = "thing2"
}

Foo foo2 = new Foo{}
foo2.prop1 = foo.prop1
foo2.prop2 = foo.prop1

If you have a lot of properties, that's a lot of lines of code I have to write.   Also, each time I add a new property, I need to change code.  Yes, you could use reflection to copy the object (and there might be a convenience library or something in C# that I'm forgetting). In many languages, you have to do the same monotony to get a copy of an object.

In Go, it's much simpler.   Every time you de-reference an object, you get a copy.  For example:
foo := &Foo{}
foo2 := *foo
Hey, I have a new copy! 

If you're working with a slice, channel, or some other object reference, it's not as simple.  But for a simple POGO from a custom struct, it's quite simple.  

Comments

Popular Posts