How can I insert new items into a map

agolangf · · 458 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I just want to know if there is a way in go to expand a map. A bit like python&#39;s append() function thanks in advance</p> <hr/>**评论:**<br/><br/>natefinch: <pre><pre><code>m := map[string]bool{ &#34;foo&#34; : true } m[&#34;bar&#34;] = false </code></pre> <p><a href="https://blog.golang.org/go-maps-in-action" rel="nofollow">https://blog.golang.org/go-maps-in-action</a></p></pre>terramorpha: <pre><p>If i initialize an empty map, it gives me a nil map error. By creating it with one value, just like you did, will it be capable of being expanded ?</p></pre>natefinch: <pre><p>Yeah, so maps have to be initialized to be able to write to them (it&#39;s a quirk of how maps are created in the runtime).</p> <pre><code>var foo map[string]bool </code></pre> <p>This creates the <em>zero value</em> for a map, which is a nil map. Nil maps panic if you try to set values on them.</p> <pre><code>foo := map[string]bool{} bar := make(map[string]bool) </code></pre> <p>These two are equivalent, and initialize a non-nil map that has no items in it. You can set values in them.</p> <pre><code>foo := make(map[string]bool, 500) </code></pre> <p>For the make version of creating a map, you can give it a size hint, which helps the runtime set up memory to store the right number of variables. This can prevent the code from wasting memory by allocating too little for the map and then having to recreate it bigger when you add more items than it in it.</p></pre>terramorpha: <pre><p>thanks lot, i am now able to continue my journey towards mastering golang</p></pre>: <pre><p>[removed]</p></pre>ChristophBerger: <pre><p>Your question is perfectly valid as there <em>is</em> a difference between slices (<code>append()</code> works fine with a <code>nil</code> slice) and maps (m[&#34;foo&#34;] = &#34;bar&#34; does not work with a <code>nil</code> map) that may not be apparent to newcomers.</p> <p>Consider <code>append()</code> as a convenience function for slices to manage dynamic size behind the scenes, which, as a side benefit, also takes care of letting a slice &#34;magically&#34; spring into existence if it is <code>nil</code> before the first append(). Maps grow dynamically by default and so they don&#39;t need a convenience function like <code>append()</code>, which also means they do not spring into existence on first assignment.</p></pre>

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

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