Google News
logo
Golang - Interview Questions
What is "slice" in Golang?
Slice in Go is a lightweight data structure of variable length sequence for storing homogeneous data. It is more convenient, powerful and flexible than an array in Go. Slice has 3 components:
 
Pointer : This is used for pointing to the first element of the array accessible via slice. The element doesn’t need to be the first element of the array.
Length : This is used for representing the total elements count present in the slice.
Capacity : This represents the capacity up to which the slice can expand.

For example : Consider an array of name arr having the values “This”,“is”, “a”,“Go”,“interview”,“question”.
package main
 
import "fmt"
 
func main() {
 
    // Creating an array
    arr := [6]string{"This","is", "a","Go","interview","question"}
 
    // Print array
    fmt.Println("Original Array:", arr)
 
    // Create a slice
    slicedArr := arr[1:4]
 
    // Display slice
    fmt.Println("Sliced Array:", slicedArr)
 
    // Length of slice calculated using len()
    fmt.Println("Length of the slice: %d", len(slicedArr))
 
    // Capacity of slice calculated using cap()
    fmt.Println("Capacity of the slice: %d", cap(slicedArr))
}
Here, we are trying to slice the array to get only the first 3 words starting from the word at the first index from the original array. Then we are finding the length of the slice and the capacity of the slice. The output of the above code would be :
Original Array: [This is a Go interview question]
Sliced Array: [is a Go]
Length of the slice: %d 3
Capacity of the slice: %d 5
Advertisement