<p>The bultin function delete() removes an element from a map if the element is present. But delete() doesn't tell us if the element was present or not. </p>
<p>So when I want to remove an element form a map and need to report an error if it wasn't present, I need to write the following:</p>
<pre><code>if _, ok := m[key]; !ok {
return errors.New("element is missing")
}
delete(m, key)
</code></pre>
<p>If delete() returned a bool set to true if an element with the corresponding key was found and deleted, I could write this:</p>
<pre><code>if !delete(m, key) {
return errors.New("element is missing")
}
</code></pre>
<p>The difference is that with the former code I need two map lookup, and the later code, I need only one. </p>
<p>People who don't care if the element is there or not when deleting the element could simply ignore the return value. </p>
<p>Is there a reason why delete doesn't return a bool ? It could also extract the value from the map and return it with the bool.</p>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传