notexOPENOverview
Notex/Languages/Converting Slices to Arrays
01.13LESSON 13 OF 33 · 2 MIN READ

Converting Slices to Arrays

Always free to read

Use a type conversion to make an array variable from a slice. You can convert an entire slice to an array of the same type, or you can create an array from a subset of the slice.

When you convert a slice to an array, the data in the slice is copied to new memory. That means that changes to the slice won’t affect the array, and vice versa.

The following code:

xSlice := []int{1, 2, 3, 4}
xArray := [4]int(xSlice)
smallArray := [2]int(xSlice)
xSlice[0] = 10
fmt.Println(xSlice)
fmt.Println(xArray)
fmt.Println(smallArray)

prints out:

[10 2 3 4]
[1 2 3 4]
[1 2]

The size of the array must be specified at compile time. It’s a compile-time error to use [...] in a slice to array type conversion.

While the size of the array can be smaller than the size of the slice, it cannot be bigger. Unfortunately, the compiler cannot detect this, and your code will panic at runtime if you specify an array size that’s bigger than the length (not the capacity) of the slice. The following code:

panicArray := [5]int(xSlice)
fmt.Println(panicArray)

panics at runtime with the message:

panic: runtime error: cannot convert slice with length 4 to array
     or pointer to array with length 5

Note

I haven’t talked about pointers yet, but you can also use a type conversion to convert a slice into a pointer to an array:

xSlice := []int{1,2,3,4}
xArrayPointer := (*[4]int)(xSlice)

After converting a slice to an array pointer, the storage between the two is shared. A change to one will change the other:

xSlice[0] = 10
xArrayPointer[1] = 20
fmt.Println(xSlice) // prints [10 20 3 4]
fmt.Println(xArrayPointer) // prints &[10 20 3 4]

Pointers are covered in the related discussion.

You can try all of the array type conversions on The Go Playground.

In “Arrays—Too Rigid to Use Directly”, I mentioned that you can’t use arrays as function parameters when the size of the array being passed in might vary. Technically, you can work around this limitation by converting an array to a slice, converting the slice to an array of a different size, and then passing the second array in to a function. The second array must be shorter than the first array, or your program will panic. While this might be helpful in a pinch, if you find yourself doing this frequently, strongly consider changing your function’s API to take a slice instead of an array.

Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K