</bugz loading .
In go, slice is a collection of similar data elements. It doesn't have a fixed size unlike an array. It is much more powerful and flexible than an array. For better understanding of arrays click here. Unlike python, slices are a separate data type in golang.
A slice has three components :
Pointer : A pointer points to the first element of the slice.
Length : The length of a slice is the number of elements present in a slice. It can be found out by using the len function.
Capacity : The capacity of a slice is the number of elements that can be inserted into a slice. It can be found out by using the cap function.
There are many ways in which we can initialise a slice, some of the simple ways are :
var s []int
In the above code :
s is the name of the slice.
int is the datatype of the elements that are going to be stored in the slice.
s = []int{9,3,5,1,8}
In the above code :
9,3,5,1,8 are the integer elements of slice.
s = make([]int,5)
In the above code :
5 is the length of the slice.
One of the easiest way to iterate over a slice is to use the range keyword.
s = []string{"one","two","three"}
for index,value := range s {
fmt.Println("The value at index",index,"is",value)
}
The value at index 0 is one
The value at index 1 is two
The value at index 2 is three
The indexing of elements in slices is similar to arrays. It starts with a 0 and ends with 1 less than the length of the slice.
The index of the first element is 0, then it kept on incrementing with the elements until the index is ( length of the slice - 1). The length of the slice is 3, hence the index of the last element of the slice is 2.
Returning a value at an index is similar for slices and arrays.
slice_name[index_number]
s := []int{5,6,4,2,9}
fmt.Println("The value at index 3 is",s[3])
The value at index 3 is 2
Unfortunately, there is no in-built mmethod for slices to check if they contain an element, but this can be done using a loop. if we want to search for an element, we basically iterate over the slice and compare every element of it with the element required, if it matches , the loop will be break else it will continue looping until it reaches the last element of the loop.
point := 0
s := []int{3,4,6,2,1}
//checking if the slice contains 6
for i,v := range s{
if v == 6 {
point = 1
fmt.Println("The element is found at index",i)
break
}
}
if point == 0 {
fmt.Println("The slice doesn't contain the element")
}
The element is found at index 2
Any number of elements can be added to the slice using the append function. The append function returns a new slice which is formed by combining the slice with the given elements.
slice_name = append(slice_name,elements_to_be_appended)
s = append(s,"four","five","six")
The append function actually returns a new slice containing the elements of the old slice and the new elements given to it.
Copying one slice to another means copying all the elements from one slice to another slice. This can be done by the copy function. It returns the number of elements copied from one slice to another.
s1 := []int{1,2,3}
s2 := []int{6,5,7}
fmt.Println("S1 :",s1)
fmt.Println("S2 :",s2)
no := copy(s1,s2) // copying s2 into s1
fmt.Println("Copied ")
fmt.Println("S1 : ",s1)
fmt.Println("Number of elements copied :",no)
S1 : [1 2 3]
S2 : [6 5 7]
Copied
S1 : [6 5 7]
Number of elements copied : 3
Slicing is the process of dividing a given slice into sub-parts. We know that slice_name[index_number] returns the element that is present at the index_number in a slice. We can also return a sub-part of the slice using the square brackets []. In the square brackets instead of one index number, we have to put the index number from which you want to slice : the index number till which you want to slice.
slice_name[from:to]
The above code returns all the elements from the index from till the index to, not including the element at to.
NOTE : If the from and to indexes are not specified, it will be assumed that the from value is 0, and the to value is the length of the slice.
s = []int{6,9,8,4,5,7}
fmt.Println(s[1:3])
fmt.Println(s[:4])
fmt.Println(s[2:])
fmt.Println(s[:])
Output
[9 8]
[6 9 8 4]
[8 4 5 7]
[6 9 8 4 5 7]
According to google concatenating is linking objects together as a chain. In simple words it is attaching one slice at the end of other. This can be achieved using the append function.
new_slice := append(slice_1,slice_2...)
The above code attaches the slice_2 at the end of the slice_1 and returns the merged slice.
s1 := []int{0,1,2}
s2 := []int{3,4,5}
s3 := append(s1,s2...)
fmt.Println(s3)
Output
[0 1 2 3 4 5]
There are several ways in which you can remove an element from a slice, one of the easiest way is to use the append function again. Yes, the append function is used to insert , as well as remove elements from a slice.
We actually divide the slice into two parts, one part contains all the elements before the element we want to remove, another part contains all the elements after the element we want to remove. Then we join both the slices using the append function.
s := []int{9,6,4,7,1,8,2,5}
fmt.Println(s)
s = append(s[:3],s[4:]...)
fmt.Println(s)
Output
[9 6 4 7 1 8 2 5]
[9 6 4 1 8 2 5]
As the element 7 is at index 3 in the code above, the s[0:3] is the part of slice that contains all the elements from index 0 to index 3, not including element at index 3. The s[4:] is the part of the slice that contains all the elements starting from index 4 to the last element. Now we join both the sub-slices into one new slice.
Sorting an integer slice is very easy. A new package ( sort ) should be imported. Now, the Ints method can be used to sort a slice of integers elements only.
import (
"fmt"
"sort"
)
func main(){
s := []int{9,4,8,6,1,5,3,2,7}
sort.Ints(s)
fmt.Println(s)
}
Output
[1 2 3 4 5 6 7 8 9]
We can check whether a slice is sorted or not using the IntsAreSorted method. This returns a boolean value, true if the slice is sorted, false if the slice is not sorted.
import (
"fmt"
"sort"
)
func main(){
s := []int{9,4,8,6,1,5,3,2,7}
fmt.Println("Before :: Sorted ? : ",sort.IntsAreSorted(s))
sort.Ints(s) // sorting the slice
fmt.Println("After :: Sorted ? : ",sort.IntsAreSorted(s))
}
Before :: Sorted ? : false
After :: Sorted ? : true
Checking whether two slices are the same / equal can be done using the DeepEqual method in the reflect package. It returns true if the slices are equal, false if they are different.
package main
import (
"fmt"
"reflect"
)
func main(){
s1 := []string{"hi","hello"}
s2 := []string{"hi","hello"}
fmt.Println("The string slices are equal ? ",reflect.DeepEqual(s1,s2))
i1 := []int{1,2,3}
i2 := []int{3,4,5}
fmt.Println("The integer slices are equal ? : ",reflect.DeepEqual(i1,i2))
}
The string slices are equal ? : true
The integer slices are equal ? : false
In this tutorial we have learnt how to create a slice, how to add elements to it, how to remove an element and many basic operations on slices. We hope that this tutorial was useful to you & you have gained some knowledge from it. Thank you :)