Like most programming languages Go also has arrays, but arrays are rarely used in Go.
/* Declearing array here [5] is the limit of array, int is the type of elements and
{elements}
*/
var arry = [5]int {1,2,3,4,5}
/* Declearing array here [...] means array limit is not fixed, int is the
type of elements and {elements}
*/
var arry = [...]int {1,2,3,4,5,6,... ...}
In Go language we use a slice more than an array, it holds the sequence of values. Slice removes the limitations of arrays.
// One dimensional Slice.
var slice = []int {1,2,3,4,5}
// Multidimensional Slice.
var multi_slice = [][]int
Using [...] makes an Array and using [] makes a Slice
// Array
var arry = [5]int {1,2,3,4,5}
//Slice
var slice = []int {1,2,3,4,5}
package main
import (
"fmt"
)
func main() {
var x []int
x = append(x, 4, 3, 4, 5, 6, 7)
fmt.Println(x[:4])
}
//Output : 4 3 4 5
Note: When we are slicing the slice we must use a Positive number cause Index must be positive.
The built-in append function is used for appending data in slice.
package main
import (
"fmt"
)
func main() {
var x []int
x = append(x, 4, 3, 4, 5, 6, 7)
fmt.Println(x)
}
There is no loop without for loop in Go, we can use both do and while in go using for loop