How do I initialize an array without using a for loop in Go?

巧了我就是萌 提交于 2019-12-04 09:49:51
icza

Using a for loop is the simplest solution. Creating an array or slice will always return you a zeroed value. Which in case of bool means all values will be false (the zero value of type bool).

Note that using a Composite literal you can create and initialize a slice or array, but that won't be any shorter:

b1 := []bool{true, true, true}
b2 := [3]bool{true, true, true}

If you don't want to use a for loop, you can make it a little shorter by introducing a constant for the value true:

const T = true
b3 := []bool{T, T, T}

If n is big, for is the simplest solution.

Or you could switch the logic of your application, and use the array or slice to store the negated values in the slice, and that way the "all-false" zero value would be a good initial value. What I mean is that if your slice is to store if files are present, you could change the logic so the slice stores whether files are missing:

presents := []bool{true, true, true, true, true, true}

// Is equivalent to:

missings := make([]bool, 6) // All false
// missing=false means not missing, means present)

Also note that filling an array or slice with a specific value is known as a "memset" operation. Go does not have a builtin function for that, but for an efficient solution see this question:

Is there analog of memset in go?

Make initilization using range function without knowing the number of elements in the array.

for i,_:=range(A){A[i] = true}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!