Does golang have a good way to initialize arrays?

polaris · · 390 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;d like to initialize an array with a value rather than the default. I was hoping make() could do this, but it can&#39;t. Not having much luck in my searches, so is there a way?</p> <hr/>**评论:**<br/><br/>mibk: <pre><p>There are many ways. It also depends on whether you want an array or a slice.</p> <pre><code>var ( a1 = [...]int{3, 4, 5} a2 = [5]int{2: 15} s1 = []int{3, 4, 5} s2 = []int{5: 10, 10: 20} ) </code></pre></pre>R2A2: <pre><p>Huh, I never knew you could define the index. I guess I never wanted to either, but it&#39;s good to know</p></pre>TheMerovius: <pre><p>The good way is to iterate over it. There is no better way, as it&#39;s the best way ;) I.e. every kind of builtin or whatever would do the same thing anyway and this way it&#39;s at least obvious what is happening and that it&#39;s an O(n) operation. It&#39;s also only one line of trivial code, so who cares?</p></pre>cristiandeives: <pre><p>You can specify the values you want with:</p> <pre><code>s := []int{0, 1, 2, 3} </code></pre> <p>You can&#39;t, however, specify one single value and the size of the slice and have that value to be applied to every position. You have to loop for that.</p></pre>kelthan: <pre><p>foo := [10]int{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, }</p></pre>

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

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