Golang Slice
Golang Slice is an abstraction over Array. While Arrays cannot be expanded or shrinked in size, Slices are dynamically sized. Golang Slice provides many inbuilt functions, which we will go through them in this tutorial.
Declare a Slice
To declare a golang slice, use var
keyword with variable name followed by []T
where T denotes the type of elements that will be stored in the slice.
var slicename []T
where slicename is the name using which we can refer to the slice.
Initialize a Slice
You can initialize a Golang Slice with elements or you can specify the size and capacity of the Slice with no initial values mentioned.
example.go
package main
import "fmt"
func main() {
var numbers []int
numbers = []int {5, 1, 9, 8, 4}
fmt.Println(numbers)
}
Output
[5 1 9 8 4]
You can also combine the declaration and initialization into single statement.
var numbers = []int {5, 1, 9, 8, 4}
Using short variable declaration, we can skip using var keyword as well. So, the code snippet for initializing a slice with predefined values boils down to
numbers := []int {5, 1, 9, 8, 4}
If you would like to initialize with a size and capacity, use the following syntax.
// declaration and initialization
var numbers = make([]int, 5, 10)
// or
// short variable declaration
numbers2 := make([]int, 5, 10)
Access Elements of Slice
We can use indexing mechanism to access elements of a slice. In the following example, we initialize a slice and access its elements at index 2
and 3
.
example.go
package main
import "fmt"
func main() {
var numbers = []int {5, 8, 14, 7, 3}
// access elements of slice using index
num2 := numbers[2]
num3 := numbers[3]
fmt.Println("numbers[2] : ", num2)
fmt.Println("numbers[3] : ", num3)
}
Output
numbers[2] : 14
numbers[3] : 7
Length and Capacity of a Slice
Slice has two properties regarding the number of elements present in slice (length) and the number of elements it can accommodate (capacity).
example.go
package main
import "fmt"
func main() {
// declaration and intialization
var numbers = make([]int, 5, 10)
fmt.Println("Size of slice: ", len(numbers))
fmt.Println("Capacity of slice: ", cap(numbers))
}
Output
Size of slice: 5
Capacity of slice: 10
Append Element
To append an item to a Golang Slice, you can use append() function. In the following example, we have initialized a Golang Slice, and we shall append an item to the Slice.
example.go
package main
import "fmt"
func main() {
var numbers = []int {5, 8, 14, 7, 3}
numbers = append(numbers, 58)
fmt.Println(numbers)
}
Output
[5 8 14 7 3 58]
Conclusion
In this Golang Tutorial, we learned how to Declare a Golang Slice, Initialize it, Access Elements of a Slice, find its Size and Capacity, with example programs.