Skip to content

How to Convert an Array Into a Slice in Go

Some functions need a slice ([]string, []int, …) but you have an array (for example: [3]string, [10]int). Converting an array is as easy as calling your array with a colon [:].

mySlice := myArray[:]

Yes it is simple, take a look at this snippet:

package main

import "fmt"

func main() {
	myArray := [5]string{"a", "b", "c", "d"}

	mySlice := myArray[:]

	fmt.Printf("%T %v \n", myArray, myArray)
	fmt.Printf("%T %v \n", mySlice, mySlice)

Leave a Reply

Your email address will not be published. Required fields are marked *