go-tutorial

Go Slices

Go Slice is a Go Array abstraction. Go Array allows you to define variables that can hold multiple data items of the same type, but it doesn’t have any built-in methods for dynamically increasing their size or getting their own sub-array. Slices get around this problem. It is commonly used in Go programming and provides numerous utility methods required on

Array.

Create slice in Golang

Here’s how we create a slice in golang:

numbers := []int{1, 2, 3, 4, 5}

Here,

  • numbers – name of the slice
  • int – represents that the slice only includes integer numbers
  • {1, 2, 3, 4, 5} – elements of the slice

You might have noticed that we have left the [] notation empty. This is because we can add elements to a slice that will change its size.

Note: If we provide size inside the [] notation, it becomes an array. For example,

// this is an array 
  numbers := [5]int{1, 2, 3, 4, 5}
// this is a slice 
   numbers := []int{1, 2, 3, 4, 5}

Example Golang Slice

// Program to create a slice and print its elements
package main 
import "fmt"
 func main() {
// declaring slice variable of type integer 
  numbers := []int{1, 2, 3, 4, 5}
// print the slice 
 fmt.Println("Numbers: ", numbers)
}

Output

Numbers: [1 2 3 4 5]

In the above example, we have created a slice named numbers. Here, int specifies that the slice numbers can only store integers.

Note: We can also create a slice using the var keyword. For example,

var numbers = []int{1, 2, 3, 4}

Create slice from an array in Golang

In Go programming, we can also create a slice from an existing array. For example, Suppose

we have an array of numbers

numbers := [8]int{10, 20, 30, 40, 50, 60, 70, 80}

Now, we can slice the specified elements from this array to create a new slice.

Here,

  • 4 is the start index from where we are slicing the array element
  • 7 is the end index up to which we want to get array elements

While creating a slice from an array, the start index is inclusive and the end index is exclusive. Hence, our slice will include elements [40, 50, 60].

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *