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:
R2A2: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} )
TheMerovius:Huh, I never knew you could define the index. I guess I never wanted to either, but it's good to know
cristiandeives: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?
kelthan: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.
foo := [10]int{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, }
