You can initialize an array with pre-defined values using an array literal. An array literal have the number of elements it will hold in square brackets, followed by the type of its elements. This is followed by a list of initial values separated by commas of each element inside the curly braces.
To create String Array, which is to declare and initialize in a single line, we can use the syntax of array to declare and initialize in one line as shown in the following. arrayName is the variable name for this string array. arraySize is the number of elements we would like to store in this string array.
To create an array you'd use [N]type{42, 33, 567} or [...] type{42, 33, 567} — to get the size inferred from the number of member in the initializer. ^Sure, I guess in Go you use arrays so rarely and the syntax is so similar that I basically interchange the two even if they are different things.
Elements of an array are accessed through indexes. The first index is 0. By default, empty arrays are initialized with zero values (0, 0.0, false, or "").
func identityMat4() [16]float64 {
return [...]float64{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 }
}
(Click to play)
If you were writing your program using Go idioms, you would be using slices. For example,
package main
import "fmt"
func Identity(n int) []float {
m := make([]float, n*n)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if i == j {
m[i*n+j] = 1.0
}
}
}
return m
}
func main() {
fmt.Println(Identity(4))
}
Output: [1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1]
How to use an array initializer to initialize a test table block:
tables := []struct {
input []string
result string
} {
{[]string{"one ", " two", " three "}, "onetwothree"},
{[]string{" three", "four ", " five "}, "threefourfive"},
}
for _, table := range tables {
result := StrTrimConcat(table.input...)
if result != table.result {
t.Errorf("Result was incorrect. Expected: %v. Got: %v. Input: %v.", table.result, result, table.input)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With