As the title says, let's say i have object o which i need to update inside function.
Now, which way of editing it is better?:
func EditObj(o Object) Object{ //body of function }
OR
func EditObj(o *Object) { //body of function }
评论:
titpetric:
jamesog:As always the answer is "it depends". If you need to create a copy of the object, you might be better with the first notation. Here's an example of such functional options, or you should read this article: Functional options for friendly APIs - Dave Cheney.
Judging by your first sentence, "I have object which I need to be changed in function" - you don't need a copy (no allocations), and you would use something like your second function to modify it.
kerakk19:Make the function a method.
func (o *Object) EditObj() { // ... }
jamesog:Function where i'm passing my object is a method to other object :)
jerf:Can you update your question then? You didn't say that.
francoishill:Then that method might want to prepare a set of arguments, then pass it to a method on o. Objects modifying other objects is generally a code smell, at the very least. There's a few exceptions where it's worth it, but they're somewhat rare.
jerf:It totally depends on your use-case. Your first option will copy the object and duplicate its memory used. It will also be used if you do not want the "consumer" to be able to modify the "original" object.
dilap:I tend to shy away from making copies in Go because the shallow copy you get can be complicated to understand if it has anything other than simpler days types. Better to just mutate, and be very careful about what you pass between goroutine boundaries.
Does Object contain any pointers (or pointer-like types -- maps, slices, or channels)? Then definitely pass a pointer and mutate.
Otherwise, either way.
If you find yourself wanting to keep both copies, then maybe prefer making a copy. Otherwise, the mutate form is also fine.
