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
-
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.
-
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.
-
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.
-
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!