Slice is a collection of similar types of data, just like arrays.
However, unlike arrays, slice doesn't have a fixed size. We can add or remove elements from the array.
Here's how we create a slice in Golang:
Here,
numbers - the name of the sliceint - represents that the slice only includes integer numbers{1, 2, 3, 4, 5} - elements of the sliceYou 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.
If we provide size inside the [] notation, it becomes an array. For example,
Output
In the above example, we have created a slice named numbers. Here, int specifies that the slice numbers can only store integers.
We can also create a slice using the var keyword. For example,
In Go programming, we can also create a slice from an existing array. For example,
Suppose we have an array of numbers
Now, we can slice the specified elements from this array to create a new slice.
Here,
While creating a slice from an array, the start index is inclusive and the end index is exclusive. Hence, our slice will include elements [50, 60, 70].
Output
In Go, slice provides various built-in functions that allow us to perform different operations on a slice.
| Functions | Descriptions |
|---|---|
append() | adds element to a slice |
copy() | copy elements of one slice to another |
Equal() | compares two slices |
len() | find the length of a slice |
We use the append() function to add elements to a slice. For example,
Output
Here, the code
adds elements 5 and 7 to the primeNumbers.
We can also add all elements of one slice to another slice using the append() function. For example,
Output
Here, we have used append() to add the elements of oddNumbers to the list of evenNumbers elements.
We can use the copy() function to copy elements of one slice to another. For example,
Output
In the above example, we are copying elements of primeNumbers to numbers.
Here, only the first 3 elements of primeNumbers are copied to numbers. This is because the size of numbers is 3 and it can only hold 3 elements.
The copy() function replaces all the elements of the destination array with the elements.
We use the len() function to find the number of elements present inside the slice. For example,
Output
In Go, we can use a for loop to iterate through a slice. For example,
Output
Here, len() function returns the size of a slice. The size of a slice numbers is 5, so the for loop iterates 5 times.