Golang Slice


January 8, 2022, Learn eTutorial
1616

In this tutorial, we will be discussing the Go slice data type which falls under the reference data type of composite types. Here you will gain knowledge of what exactly is a slice in Golang, their definition and declaration syntax in Golang, copy, append, move functions used in Golang, etc

What is a slice in Golang?

A slice is a reference type data structure that represents a sequence of elements of the same type of an existing or underlying array. A slice refers to a piece or section of an existing array.  Like arrays, a slice does not have its own data it only provides a reference to a particular section of data/elements in an array.   

  •     Slices are flexible, dynamically sized i.e. size of the slice can be resized; they are not fixed like an array.
  •     Unlike arrays, a slice does not store any data.
  •     Slices are to represent a section of the underlying array.
     

Let us understand the slice concept in an easier manner with a simple Array representation:

GO : Slice

The above figure shows an array “A” with index 0, 1, 2………9.Each array index stores some string-type elements. For example, an array with index 0, A [0] contains “LET”, A [1] contains “US” etc….(for better understanding of array refer to array tutorial).

Now let us understand how the slice works with the array. Array A is going to be partitioned into two slices. The two slices Slice 1 & slice 2 of A form subset of the underlying array.

GO : Slice

How to declare and initialize a slice in Golang?

Declaration of the slice is similar to an array. The only exception compared to the array is the size of the slice needs not be prespecified.

For eg the square [ ] bracket remains empty in slice declaration while in the case of arrays some values are specified inside the square bracket like [5],[7] to initialize the array size. Based on slice requirements the size of the slice expands and compresses accordingly.

Syntax :

An empty square bracket [ ], followed by any of the declaration types discussed in the array tutorial.


[ ] arrDec
 Or 
[ ] arrDec{ }
Or
[ ] arrDec{value1, value 2, value 3 …………..value m}

In the above syntax, arrDec represents the types of selected array declaration.

GO : Slice

Golang program to illustrate how to create a slice using a slice literal & shorthand notation


package main
import "fmt"
 
func main() {
 
    // Creating a slice
    // using the var keyword
    var slice1 = []string{"learn", "e", "tutorials"}
 
    fmt.Println(" Slice 1:", slice1)
 
    // Creating a slice
    //using shorthand declaration
    slice2 := []int{ 67, 67,56,98, 43 }
    fmt.Println(" Slice 2:", slice2)
    }

Output:


Slice 1: [learn e tutorials]
Slice 2: [67 67 56 98 43]

Make ( ) function in a slice of Golang

Make function in Golang creates a new slice. It is a built-in function.

  •   The syntax is represented with the make ( ) function, inside bracket contains parameters type, length, and capacity. Capacity is optional.           
  •   The make (  ) allocates the underlying array of size equal to provided capacity.
  •   make() returns slice that refers to that portion of the array.

Syntax :


make([]arrDec, len, cap) []arrDec

Program Creation of slice with make()


package main
import "fmt"

func main() {
   // Creating slice using make function
   A := make([]string, 5)  
   //initially empty
    fmt.Println("array A is: ", A) 
   //assigning values to slice array
    A[0] = "Golang"
    A[1] = "in"
    A[2] = "learn"
    A[3] = "e"
    A[4] = "tutorials"

    fmt.Println("slice created using make(): ", A)
}

Output:


array A is:  [    ]
slice created using make():  [Golang in learn e tutorials]

Explanation: 

  •   Created a slice of string type having the capacity to hold 5 elements by providing size as 5 with the make function. 
  •   Once after slice is created, it is empty with no values. Default values are set. In case of string empty space or in case of integers 0.
  •   In the next step, new values are assigned to the slice.
     

How to slice an array /Creation of slice in Golang?

  •   A slice is created by slicing a subset from the underlying or existing array.
  •   In order to slice we need to define the range of elements to be sliced within square brackets.
  •   The range defines lower bound from where slice begins till a high bound, The syntax looks like A [LOW: HIGH], in this case, excludes the last element.
  •   The default value is zero for the low bound and slice length is also zero for the high bound.
  •   Example The slice 1 is within the range [2:6], 6 the element is excluded., Below the given program explains the same concept.
     

Golang program to illustrate the creation of a slice


package main
import "fmt"
 
func main() {
 
    // Creating an array
    A:= [10]string{"Let", "us", "learn", "Go",
                         "programming", "language", "with","learn ","e","tutorials"}
 
    // Display array
    fmt.Println("Array A:", A)
 
    // Creating a slice
    slice1:= A[2:6] // start from index 2 till 5
    
    slice2 :=A[:2] //start from index 0 till 1 excludes index 2
    
    slice3 := A[7:] //start from 7 till ending index
    
    slice4 := A[:]
 
    // Display slice
    fmt.Println("Slice 1 is :", slice1)
    fmt.Println("Slice 2 is :", slice2)
    fmt.Println("Slice 3 is :", slice3)
    fmt.Println("Slice 4 is :", slice4)
}

Output:


Output
Array A: [Let us learn Go programming language with learn  e tutorials]
Slice 1 is : [learn Go programming language]
Slice 2 is : [Let us]
Slice 3 is : [learn  e tutorials]
Slice 4 is : [Let us learn Go programming language with learn  e tutorials]

What are Slice Internals/Slice Components?

The slice internals is the components that make up a slice. A slice is internally represented with a pointer to the array, with its length and capacity. We know slice is a segment of an array with these three components so it can be generalized with the below syntax.

  1. Pointer
  2. Length
  3. Capacity

type Slice struct {
    array unsafe.Pointer
    cap   int
    len   int
}

What is a Pointer in a slice?

A pointer points to the initial element of the slice in the array. In the given example for slice 1 containing elements

[“LEARN”,” GO”,” PROGRAMMING”,” LANGUAGE]

GO : Slice

Here initial or beginning element is learned with index 2 so the pointer points to that location. Therefore pointer is set to 2

How to Find the Length of a slice?

The length of the slice is the number of elements in the slice.len() function in the slice is used to determine the length of a slice. In the below-given slice 1, there is a total of 4 elements starting from the beginning. Therefore length is set to 4.

Slice1 ---- > [“LEARN’ “Go”,” PROGRAMMING” “LANGUAGE “]

len(slice1) returns the number of elements present in slice 1 ie, len(slice1) call returns a value 4

What is the capacity of a slice in Golang?

The capacity of a slice is the maximum number of elements in the underlying array. cap() function in slice determines the capacity of the slice.In the below example start counting from the beginning of slice1 elements till the end of the underlying array

GO : Slice

So counting from slice 1 index beginning till array ending position denotes the capacity for an above slice which returns an integer value 8. It can be denoted as cap(slice) =8.

The below picture depicts the internal components of slice 1 with pointer points to array address 2, length of the segment is 4, and capacity of slice 1 is 8 since slice 1 is a segment of Array A with actual size 10 (0,1,2…..9 index) in which index from 2 to 5  segment form slice1  together with the remaining index starting from 6 to ending at index 9 forms the total capacity i.e. capacity equals to 8. (with respect to the above example discussed)

GO : Slice

Let us understand the above-discussed len( ) and cap( ) function using Golang. The same description we have discussed is coded in the below Go program.

Golang program to illustrate the working of the slice len(),cap()


package main
import "fmt"
 
func main() {
 
    // Creating an array
    A:= [10]string{"Let", "us", "learn", "Go",
                         "programming", "language", "with","learn ","e","tutorials"}
 
    // Display array
    fmt.Println("Array:", A)
 
    // Creating a slice
    slice1:= arr[2:6]   //slicing array
 
    // Display slice
    fmt.Println("Slice 1 is :", slice1)
 
    // Display length of the slice
    fmt.Printf("Length of the slice 1: %d", len(slice1))
 
    // Display the capacity of the slice
    fmt.Printf("\nCapacity of the slice 1: %d", cap(slice1))
}

Output:


Output
Array A: [Let us learn Go programming language with learn  e tutorials]
Slice 1 is : [learn Go programming language]
Length of the slice 1: 4
Capacity of the slice 1: 8

How to append elements to a slice?

Append () function is a built-in function in a slice that appends elements to a slice.
Alternatively, append () allows expanding the size of the slice.

Program to append in a slice


package main
import "fmt"

func main() {
// slice creation using make()
  A := make([]string, 3)
//dispplays initial slice values
    fmt.Printf("slice:%v; len: %d; cap: %d \n", A, len(A), cap(A))

    fmt.Println("---------------------------")
//performs appending values to slice A
    A = append(A, "Go")
    A = append(A, "Lang")
    A = append(A, "in")
    A = append(A, "learn", "e", "tutorials")
//display slice after insertion
    fmt.Printf("slice: %v; len: %d; cap: %d \n", A, len(A), cap(A))
}

Output:


slice:[  ]; len: 3; cap: 3 
---------------------------
slice: [   Go Lang in learn e tutorials]; len: 9; cap: 12 

  •   In the above example, three elements are declared using the make () function in the slice. The empty slice is of string type with length & capacity 3.
  •   Six elements Go Lang in learning e tutorials are appended to the slice A, which expands slice by length 9 and capacity 12.

How to copy in a slice?

Copy () function is a built-in function that allows copying elements from one slice (source slice) to another slice (destination slice).

Program to copy slice


package main
import "fmt"

func main() {
// slice creation using make()
  A := []string {"Go", "lang"}
  B :=make([]string,len(A))
//displays initial slice values
    fmt.Printf("Initial slice A:%v; len: %d; cap: %d \n", A, len(A), cap(A))

    fmt.Println("---------------------------")

   copy1 := copy(B,A)
//display slice after COPYING
   
    fmt.Printf("%d elements copied\n", copy1)
    fmt.Printf("slice after copying to B: %v; len: %d; cap: %d \n", B, len(B), cap(B))
}

Output:


Initial slice A:[Go lang]; len: 2; cap: 2 
---------------------------
2 elements copied
slice after copying to B: [Go lang]; len: 2; cap: 2 

In the above program copied slice is declared in A to slice B of string type by using the copy( ) function.

Iteration in Golang slice?

In slice for loop is used for iteration among slice elements.


package main

import "fmt"

func main() {

   tutorial := []string{"Go", "Programming", "language", "in", "learn", "e","tutorials"}

    for a, tutorial := range tutorial {

        fmt.Println(a, tutorial)
    }
}

Output:


0 Go
1 Programming
2 language
3 in
4 learn
5 e
6 tutorials

Difference between array & slice

S.No ARRAY SLICE
1 Array stores sequence of elements of the same type Slice does not store any data
2 The array has a fixed size Slice is flexible can be resized
3 Arrays are less used in Go Slice is most used in Go
4 Array copies refer to different underlying data Slice copies refer to the same underlying data