Go Slices

Last Updated: March 20, 2022

Slice is more powerful, flexible, and convenient than an array but the slice is built on top of the array

Slice is dynamic-sized ( You can add or remove elements dynamically)

The type []T is a slice with elements of type T.

How to create a slice

package main

import (  
    "fmt"
)

func main() {  
    a_array := [5]int{10, 20, 30, 40, 50}
    var b_slice []int = a[1:4] //creates a slice from a[1] to a[3]
    fmt.Println(b_slice)
}

Another way to create a slice

package main

import (  
    "fmt"
)

func main() {  
    s := []int{10, 20, 30} //creates and array and returns a slice reference
    fmt.Println(s)

}

Other ways to create a slice

s := []int{10,20,30,40,50,60}
b := s[:] // slice all elements
c := s[3:] // slice from fourth element to end
d := s[:4] // slice first four elemnts
e := s[3:5] // slice from third ,fourth and fifth elements

Using make() to create a slice

s := make([]int,3)
fmt.Println("slice:", s) // slice: [0 0 0]

s := make([]int,3,100) // capacity of the slice is 100

Length and capacity of the slice

Length of the slice = len(marksslice)

The capacity of the slice = cap(marksslice)

Slices are reference type

Slices in GO are reference types but arrays in GO are value type

package main

import "fmt"

var i int = 10

func main() {

	a := []int{56, 78, 98, 93}
	var b = a
	b[0] = 10
	fmt.Printf("%v\n", a) // [10 78 98 93]
	fmt.Printf("%v\n", b) // [10 78 98 93]
}

Add an element to slice in Golang

You can use append to add element(s) to slice in GO language

s := make([]int, 3)
s = append(s, 1)
fmt.Println(s) // [0 0 0 1]

s = append(s, 2,3,4)
fmt.Println(s) // [0 0 0 1 2 3 4]

s = append(s,[]int{5,6,7}...)
fmt.Println(s) // [0 0 0 1 2 3 4 5 6 7]

Remove the element from Slice in Golang

How to delete the 2nd element of the slice

Test