Saved Bookmarks
| 1. |
What is “slice” in Go? |
|
Answer» 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:
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: 3The capacity of the slice: 5The same is illustrated in the diagram below: |
|