How do you create an array of variable length?

agolangf · · 387 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Since Google has yielded few results other than &#34;ya don&#39;t&#34; from a few years ago, I turn to reddit. Say I&#39;m reading from a CSV, and want to append a row to an array. However, I have no clue how many rows I have, and I&#39;m reading one row at a time to save on memory. How do I make an array without knowing its exact future length? </p> <hr/>**评论:**<br/><br/>bobcrotch: <pre><p>Tl;dr: arrays are fixed length, slices aren&#39;t (but have a cost of being so).</p> <p>This is a pretty digestible explanation: <a href="https://blog.golang.org/go-slices-usage-and-internals" rel="nofollow">https://blog.golang.org/go-slices-usage-and-internals</a></p></pre>SerialMiller: <pre><p>Something like this should do the trick</p> <pre><code>numbers := make([]int, 0) numbers = append(numbers, 1) numbers = append(numbers, 2) fmt.Println(len(numbers)) // == 2 </code></pre></pre>thequux: <pre><p>Also, if you&#39;re coming from C, you might expect this to be really slow. It isn&#39;t. Slices are equivalent to</p> <pre><code>struct slice_t { size_t length, capacity; element* data; }; </code></pre> <p>When go needs to resize the underlying array, it doubles in size, so the total time taken is linear in the number of elements.</p></pre>itsmontoya: <pre><p>To add to this, if you have a rough idea of how long your array should be. Set the cap value. This way you avoid unnecessary allocations</p></pre>sacado: <pre><pre><code>var numbers []int </code></pre> <p>is a little more idiomatic (and a little more efficient) than</p> <pre><code>numbers := make([]int, 0) </code></pre> <p>AFAIK, some linters complain about the latter.</p></pre>

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

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