Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 359
abadojack Avatar asked Sep 25 '15 15:09

abadojack


People also ask

How do you manually initialize an array?

To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.

Can we declare array without initialization?

Declaring an array does not initialize it. In order to store values in the array, we must initialize it first, the syntax of which is as follows: datatype [ ] arrayName = new datatype [size]; There are a few different ways to initialize an array.

How do you assign a value to an array in Go?

In Go language, arrays are mutable, so that you can use array[index] syntax to the left-hand side of the assignment to set the elements of the array at the given index. You can access the elements of the array by using the index value or by using for loop.


1 Answers

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?

like image 58
icza Avatar answered Mar 16 '23 01:03

icza