How to Declare and Initialize an Array in one line in …
How to Declare and Initialize an Array in one line in Go?
Go ? Declare and Initialize an Array in One Line
We can declare and initialize an array in one line in Go programming.
The syntax to declare and initialize an array arrayName of size arraySize in which elements of type arrayDataType are stored is
arrayName := [arraySize] arrayDataType {value1, value2}
The initial values are given as comma separated values enclosed in curly braces as shown in the code above.
The number of initial values must be less than or equal to the array size specified.
Examples
In the following program, we declare and initialize an array arr of size 4 and type int . The initial values for this array are {1, 4, 9, 16} .
example.go package main import "fmt" func main() { arr := [4]int{1, 4, 9, 16} fmt.Println(arr) }
Output [1 4 9 16]
Now, let us provide initial values less than the specified array size.
example.go
package main import "fmt" func main() {
arr := [4]int{1, 4, 9} fmt.Println(arr) }
Output
[1 4 9 0]
If the initial values are less in number than the array size, then the default values of the specified datatype would be assigned for the rest of the values.
Conclusion
In this Golang Tutorial, we learned how to declare and initialize an array in single line in Go programming, with the help of example programs.
Golang Golang Tutorial Run Golang Program Golang If Else Golang Switch Golang For Loop Golang Comments Golang Functions Golang Array Golang Slice Golang Struct Golang Class Golang Range Golang Map
Golang Goroutine Golang Channel
Golang String Operations Golang String Length Golang String Concatenation Golang Split String Golang String - Get Index of Substr Golang String to Uppercase Golang String to Lowercase Golang Convert String to Integer
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- how to declare array in java
- how to declare an array in numpy
- how to declare a character in matlab
- how to declare string matlab
- how to declare a list java
- how to write and solve an inequality
- initialize an array python
- declare an array in c
- how to declare your sovereignty
- how to declare an arraylist java
- how to declare an array in c
- how to declare an integer in python