<p>Since Google has yielded few results other than "ya don't" from a few years ago, I turn to reddit. Say I'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'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'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're coming from C, you might expect this to be really slow. It isn'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
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传