I have object which i need to be changed in function. Should i pass it as parameter and return it or pass it as reference and edit inside function?

polaris · · 432 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>As the title says, let&#39;s say i have object o which i need to update inside function.</p> <p>Now, which way of editing it is better?:</p> <p>func EditObj(o Object) Object{ //body of function }</p> <p>OR</p> <p>func EditObj(o *Object) { //body of function }</p> <hr/>**评论:**<br/><br/>titpetric: <pre><p>As always the answer is &#34;it depends&#34;. If you need to create a copy of the object, you might be better with the first notation. Here&#39;s an <a href="https://scene-si.org/2017/02/22/store-config-in-the-environment/#best-practices">example of such functional options</a>, or you should read this article: <a href="https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis">Functional options for friendly APIs - Dave Cheney</a>.</p> <p>Judging by your first sentence, &#34;I have object which I need to be changed in function&#34; - you don&#39;t need a copy (no allocations), and you would use something like your second function to modify it.</p></pre>jamesog: <pre><p>Make the function a method.</p> <pre><code>func (o *Object) EditObj() { // ... } </code></pre></pre>kerakk19: <pre><p>Function where i&#39;m passing my object is a method to other object :)</p></pre>jamesog: <pre><p>Can you update your question then? You didn&#39;t say that.</p></pre>jerf: <pre><p>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&#39;s a few exceptions where it&#39;s worth it, but they&#39;re somewhat rare.</p></pre>francoishill: <pre><p>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 &#34;consumer&#34; to be able to modify the &#34;original&#34; object.</p></pre>jerf: <pre><p>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.</p></pre>dilap: <pre><p>Does Object contain any pointers (or pointer-like types -- maps, slices, or channels)? Then definitely pass a pointer and mutate.</p> <p>Otherwise, either way.</p> <p>If you find yourself wanting to keep both copies, then maybe prefer making a copy. Otherwise, the mutate form is also fine.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

432 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传