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
}
``````
duanqiao0153 这行不通。

douxiaochun4964 减少执行时间。

douqiang4245 出于好奇：您为什么要避免for循环？

2个回答

< p>请注意，使用复合文字，您可以创建和初始化切片或数组，但是 不会再短：</ p>

``` ``` b1：= [] bool {true，true，true}
b2：= [3] bool {true，true，true} \  n </ code> </ pre>

const T = true
b3：= [] bool {T，T，T}
</ code> </ pre>

表示：= [] bool {true，true，true，true，true，true，true}

//等效于：

missings：= make（[] bool，6  ）//所有false
// missing = false表示不丢失，表示存在）
</ code> </ pre>

中是否有类似的memset？ </ p>
</ div>``````

### 原文

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?

``` ```对于i，_：= range（A）{A [i] = true}
</ code> </ pre>
</ div>``````

### 原文

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

``````for i,_:=range(A){A[i] = true}
``````

doudang4857 对于i：=范围A [A [i] = true}