1. Introduction
Arrays and slices are both used in Go to work with collections of data. However, slices are more flexible and powerful due to their dynamic sizing capabilities. In certain situations, you might start with an array but need the features of a slice. This post will demonstrate how to convert an array to a slice in Go.
Definition
Converting an array to a slice in Go can be achieved by 'slicing' the array, which involves using a slice expression to create a slice that references the original array. This operation does not copy the array data; instead, the resulting slice is a window to the array.
2. Program Steps
1. Declare and initialize an array.
2. Convert the entire array to a slice using a slice expression.
3. Create a slice from a portion of the array.
4. Use the slice for further operations such as appending elements.
3. Code Program
package main
import "fmt"
func main() {
// Step 1: Declare and initialize an array
myArray := [4]int{10, 20, 30, 40}
// Step 2: Convert the entire array to a slice
fullSlice := myArray[:]
// Step 3: Create a slice from a portion of the array
partialSlice := myArray[1:3]
// Step 4: Use the slice to append elements
extendedSlice := append(fullSlice, 50)
// Printing the results
fmt.Println("Original array:", myArray)
fmt.Println("Full slice:", fullSlice)
fmt.Println("Partial slice:", partialSlice)
fmt.Println("Extended slice:", extendedSlice)
}
Output:
Original array: [10 20 30 40] Full slice: [10 20 30 40] Partial slice: [20 30] Extended slice: [10 20 30 40 50]
Explanation:
1. package main - The program's package is declared.
2. import "fmt" - The format package is imported for output operations.
3. myArray - An integer array is declared and initialized with four elements.
4. fullSlice - A slice expression myArray[:] is used to create a slice that includes all elements of the array.
5. partialSlice - A slice expression myArray[1:3] creates a slice from a subset of the array, including elements from index 1 up to, but not including, index 3.
6. extendedSlice - The append function is used to add an element to the slice, demonstrating how slices can be dynamically extended.
7. The fmt.Println statements print out the original array, the full slice, the partial slice, and the extended slice.
8. The output demonstrates the original array, the derived full and partial slices, and the extended slice, showing how to convert and work with an array as a slice.
Comments
Post a Comment