How to Convert an Array to a Slice in Go

1. Introduction

Arrays in Go are useful when you want a fixed-size collection of elements, but slices offer more flexibility due to their dynamic nature. At times, you may start with an array and find you need the features of a slice. This post will cover how to convert an array into a slice in Go, which allows for more dynamic operations such as appending, slicing, and passing to functions that expect a slice.

Definition

An array in Go is a numbered sequence of elements of a single type and fixed length. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. Conversion from an array to a slice is done by specifying a slice of the array.

2. Program Steps

1. Declare and initialize an array.

2. Reference the array to create a slice.

3. Perform operations on the slice, such as appending new elements.

3. Code Program

package main

import (
	"fmt"
)

func main() {
	// Step 1: Declare and initialize an array
	myArray := [5]int{1, 2, 3, 4, 5}
	fmt.Println("Array:", myArray)

	// Step 2: Reference the array to create a slice
	mySlice := myArray[:] // Creates a slice that includes all elements of the array

	// Step 3: Append a new element to the slice
	mySlice = append(mySlice, 6)
	fmt.Println("Slice:", mySlice)
}

Output:

Array: [1 2 3 4 5]
Slice: [1 2 3 4 5 6]

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package for printing the output.

3. myArray is an array that is initialized with a sequence of integers.

4. mySlice is created from myArray by using the expression myArray[:]. This creates a slice that references the entire array.

5. append is used to add an element to mySlice. This showcases one of the benefits of slices, as arrays cannot be appended to directly.

6. The program prints out the original array and the newly-formed slice.

7. The output confirms that mySlice includes all elements of myArray, plus the additional element 6.


Comments