Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Defining a Go Slice
2.1.
Syntax
2.2.
Example  
3.
Built In Slicing Function
3.1.
Syntax
3.2.
Example
4.
len() and cap() functions
4.1.
Example
5.
Nil slice
5.1.
Example
6.
Subslicing
6.1.
Example 
7.
append() function 
7.1.
Syntax 
7.2.
Example 
7.3.
Appending One Slice to Another
7.3.1.
Syntax
7.3.2.
Example
8.
copy() function
8.1.
Syntax
8.2.
Example
9.
FAQs
10.
Key takeaways
Last Updated: Mar 27, 2024

Go Slice

Author Shivam Verma
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

A slice is like an array but is more powerful, flexible, convenient than an array. Like arrays, slices can also store multiple values of the same type in a single variable. However, an array has a fixed size. On the other hand, a slice is a dynamically-sized, flexible view into the elements of an array.

Defining a Go Slice

We can declare a slice just like an array without specifying its size. So it can be resized according to the requirement.

Syntax

[ ]T

Here in the above syntax, T is the type of the elements.

Example  

Myslice1 := [ ]int
Myslice2 := [ ]int{4,2,6}

In the above examples, myslice1 is an empty slice of 0 lengths and 0 capacity, and myslice2 is a slice of integers of length 3 and the capacity of 3.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Built In Slicing Function

We can also use the make built-in function to create a slice.

Syntax

slicename := ([ ]type, length, capacity)

Here in the above syntax, the make function takes a type, a length, and an optional capacity. If the capacity parameter in the make function is not defined, it will be equal to length.

Example

package main
import "fmt"
func main(){
    marks:=make([]int, 3)
    marks[0]=87
    marks[1]=96
    marks[2]=68
    fmt.Printf("Marks= %v",marks)
}

Output

Marks= [87 96 68]

len() and cap() functions

The len() function returns elements that are present in the slice, whereas the cap() function returns the capacity of the slice, which means how many elements can be accommodated in the given slice.

Let us understand these functions with the help of an example.

Example

package main
import "fmt"
func main(){
    marks:=make([]int, 5, 8)
    len1:=len(marks)
    cap1:=cap(marks)
    fmt.Printf("Size=%d\n",len1)
    fmt.Printf("Capacity=%d\n", cap1)
    fmt.Printf("Marks=%v\n", marks)
}

Output

Size=5
Capacity=8
Marks=[0 0 0 0 0]

Nil slice

If a slice is declared with no inputs, then by default, it is initialized as nil. A nil slice has a length and capacity of zero.

Here is an example of a nil slice. 

Example

package main
import "fmt"
func main(){
   var marks []int
   fmt.Printf("Length=%d Capacity=%d\n",len(marks),cap(marks))
   if(marks== nil){
      fmt.Printf("Slice is nil")
   }
}

Output

Length=0 Capacity=0
Slice is nil

Subslicing

Slices can be re-sliced, creating a new slice value that points to the same array. To get the subslice, we use the expression [lo:hi], which evaluates to a slice of the elements from lo through hi-1. Here in the expression [lo:hi] lo and hi would be integers representing indexes.

Example 

package main
import "fmt"
func main(){
    // create a slice  
   myslice:=[]int{3,5,8,12,9,11,45,32} 
   // prints original slice
   fmt.Println("myslice=",myslice)  
    // prints a sub slice starts from index 2(included) to index 4(excluded)
   fmt.Println("myslice[2:4]=",myslice[2:4])
   // missing low index implies 0
   fmt.Println("myslice[:5]=",myslice[:5])  
   // a sub slice starts from index 4(included) to index 8(excluded)
   myslice1:=myslice[4:8]                
   fmt.Println("myslice1=",myslice1) 
   // missing high index implies 0
   myslice2:=myslice[3:]                   
   fmt.Println("myslice2=",myslice2)
}

Output

myslice= [3 5 8 12 9 11 45 32]
myslice[2:4]= [8 12]
myslice[:5]= [3 5 8 12 9]
myslice1= [9 11 45 32]
myslice2= [12 9 11 45 32]

append() function 

The append() function appends new elements to the end of a slice. 

Syntax 

func append(slice []Type, elems ...Type) []Type

In the above syntax, the first parameter of the append function is a slice itself, and the second parameter is the variable number of arguments append to the slice.

The resulting append value is a slice containing all the original slice elements plus the provided values. A bigger array will be allocated if the backing array is too small to fit all the given values.

Example 

package main
import "fmt"
func main(){
    values:=make([]int, 4)
    fmt.Printf("Length=%d Capacity=%d Values=%v\n",len(values),cap(values),values)
    values=append(values, 6)
    values=append(values, 9)
    values=append(values, 2, 56, 12)
    fmt.Printf("Length=%d Capacity=%d Values=%v\n",len(values),cap(values),values)
}

Output

Length=4 Capacity=4 Values=[0 0 0 0]
Length=9 Capacity=16 Values=[0 0 0 0 6 9 2 56 12]

Appending One Slice to Another

We can also append a slice to another using an ellipsis.

Syntax

res := append(slice_name1, slice_name2...)

In the above syntax,  '…' is an operator, which means the argument is a variadic parameter. Meaning that slice_name2 will be expanded to its individual elements during run time.

Example

package main
import "fmt"
func main(){
    values1:=[]int{10, 12, 25}
    values2:=[]int{45, 20, 55, 65}
    values:=append(values1, values2...)
    fmt.Printf("Length=%d Capacity=%d Values=%v\n",len(values),cap(values),values)
}

Output

Length=7 Capacity=8 Values=[10 12 25 45 20 55 65]

copy() function

The copy function is used to copy the contents of a source slice to a destination slice.

Syntax

func copy(dst, src []Type) int

In the above syntax, the copy function takes in two slices dst and src, and copies data from src to dst. It returns the number of elements copied, the minimum of len(dst) and len(src).

Example

package main
import "fmt"
func main(){
    values1:=[]int{13,52,75,96}  // define s src slice
    values2:=[]int{43,95,86,32,76}   // define a dst slice
    num1:=copy(values2, values1)
    fmt.Println(values2)
    fmt.Println("Number of elements copied:",num1)
    num2:=copy(values2, values2[3:]) // using the same slice as the src and dst slice
    fmt.Println(values2)
    fmt.Println("Number of elements copied:",num2)
}

Output

[13 52 75 96 76]
Number of elements copied: 4
[96 76 75 96 76]
Number of elements copied: 2

FAQs

  1. What is a slice in Golang?
    Ans: A slice is like an array but is more powerful, flexible, convenient than an array. An array has a fixed size. On the other hand, a slice has a variable size.
     
  2. How do I return a slice in Golang?
    Ans: We can use the make function in the Go language to create new slices. The make function allocates an underlying array with a size equal to the given capacity and returns a slice that refers to that array.
     
  3. What is the Golang cap() function?
    Ans: The cap() function returns the capacity of the slice, which means how many elements can be accommodated in the given slice.
     
  4. Is Golang slice ordered?
    Ans: Yes. A slice will always have a fixed order.

Key takeaways

In this article, we have extensively discussed about the Slices in Go programming language. We also discussed len() and cap() functions, nil slice, subslicing, append and copy functions with examples.

We hope that this blog has helped you enhance your knowledge regarding Go Slice and if you would like to learn more, check out our article on Arrays. You can read other C language articles by clicking here. Do upvote our blog to help ninjas grow. Happy Coding!

Previous article
Go Arrays
Next article
Go Command Arguments
Live masterclass