Go – Create String Array
In this tutorial, we will learn how to create a String array in Go: declare and initialize a string array. There are few methods based on whether we declare and initialize the array in one statement or separately.
To declare a string array arrayName, with size arraySize, use the following syntax.
var arrayName [arraySize]string
And to assign values for array elements, we can use array-index notation as shown below.
arrayName[index] = someValue
In the following example, we will declare a string array strArr of size 3, and then assign values to the elements of this string array.
example.go
package main
import "fmt"
func main() {
var strArr [3]string
strArr[0] = "Abc"
strArr[1] = "Xyz"
strArr[2] = "Mno"
fmt.Println(strArr)
}
Output
[Abc Xyz Mno]
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 := [arraySize] string {value1, value2}
where
arrayNameis the variable name for this string array.arraySizeis the number of elements we would like to store in this string array.stringis the datatype of the items we store in this array.value1, value2and so on are the initial values we would like to initialize this array with.
In the following example, we will declare and initialize a string array strArr of size 3 in a single line.
example.go
package main
import "fmt"
func main() {
strArr := [3]string{"Abc", "Xyz", "Mno"}
fmt.Println(strArr)
}
Output
[Abc Xyz Mno]
Conclusion
In this Go Tutorial, we learned how to create a string array, with the help of example programs.
