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:
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:
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.
Foo foo = new Foo{prop1 = "thing1"prop2 = "thing2"}
Foo foo2 = new Foo{}foo2.prop1 = foo.prop1foo2.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:
Hey, I have a new copy!foo := &Foo{}foo2 := *foo
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
Post a Comment