I have an array A
of boolean values, indexed by integers 0
to n
, all initially set to true
.
My current implementation is :
for i := 0; i < n; i++ {
A[i] = true
}
I have an array A
of boolean values, indexed by integers 0
to n
, all initially set to true
.
My current implementation is :
for i := 0; i < n; i++ {
A[i] = true
}
Make initilization using range function without knowing the number of elements in the array.
Using a
for
loop is the simplest solution. Creating an array or slice will always return you a zeroed value. Which in case ofbool
means all values will befalse
(the zero value of typebool
).Note that using a Composite literal you can create and initialize a slice or array, but that won't be any shorter:
If you don't want to use a
for
loop, you can make it a little shorter by introducing a constant for the valuetrue
: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:
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?