Does golang have a good way to initialize arrays?

polaris · 2016-08-31 02:00:02 · 503 次点击    
这是一个分享于 2016-08-31 02:00:02 的资源,其中的信息可能已经有所发展或是发生改变。

I'd like to initialize an array with a value rather than the default. I was hoping make() could do this, but it can't. Not having much luck in my searches, so is there a way?


评论:

mibk:

There are many ways. It also depends on whether you want an array or a slice.

var (
    a1 = [...]int{3, 4, 5}
    a2 = [5]int{2: 15}
    s1 = []int{3, 4, 5}
    s2 = []int{5: 10, 10: 20}
)
R2A2:

Huh, I never knew you could define the index. I guess I never wanted to either, but it's good to know

TheMerovius:

The good way is to iterate over it. There is no better way, as it's the best way ;) I.e. every kind of builtin or whatever would do the same thing anyway and this way it's at least obvious what is happening and that it's an O(n) operation. It's also only one line of trivial code, so who cares?

cristiandeives:

You can specify the values you want with:

s := []int{0, 1, 2, 3}

You can'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.

kelthan:

foo := [10]int{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, }


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

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