Understanding the differences between Arrays and Slices in the Go programming language, defining Arrays and Slices might look similar but it has certain amount of differences that you need to know.
declaration of Array will takes size as mentioned below, so it cannot hold elements more than 4.
// define array, limited to capacity of 4 elements
var a[4]int
Arrays do not need to be initialized explicitly; the zero value of an array is a ready-to-use array whose elements are themselves zeroed:
so the in-memory values in variable a, will be as below
[0,0,0,0]
As we have declared Array with size 4, so its size is fixed, so it cannot have capacity to hold more elements than 4.
you can define a slice same like array, but you need not to mention its size, as like below. it capacity can be grown whatever the program required at the time of execution.
var b[]int
Add element to Slice, adds element to end of Slice and returns new Slice.
b = append(b, 2);
print the slice, the slice contains 1 element with value 2
[2]
A slice can also be created with the built-in function called make. When called, make allocates an array and returns a slice that refers to that array.
var b[]int
b = make([]int, 3, 3);
print the slice, the slice contains 3 elements with 0 value.
[0 0 0]
after calling make on Slice, still slice can size grow to hold the elements with append func.
b = append( b, 1)
b = append( b, 2)
b = append( b, 3)
b = append( b, 4)
b = append( b, 5)
output:
[0 0 0 1 2 3 4 5]
The first 3 elements was created with make, other 1 to 5 elements appended with append function.
how to use range in golang
posted on 2022-05-03 08:28:11 - Go lang Tutorials
find variable type in golang
posted on 2022-05-03 05:24:55 - Go lang Tutorials