Conversions from slice to array or array pointer

March 14, 2024

Conversions from slice to array or array pointer

Converting a slice to an array yields an array containing the elements of the underlying array of the slice. Similarly, converting a slice to an array pointer yields a pointer to the underlying array of the slice. In both cases, if the length of the slice is less than the length of the array, a run-time panic occurs.

s := make([]byte, 2, 4)

a0 := [0]byte(s)
a1 := [1]byte(s[1:])     // a1[0] == s[1]
a2 := [2]byte(s)         // a2[0] == s[0]
a4 := [4]byte(s)         // panics: len([4]byte) > len(s)

s0 := (*[0]byte)(s)      // s0 != nil
s1 := (*[1]byte)(s[1:])  // &s1[0] == &s[1]
s2 := (*[2]byte)(s)      // &s2[0] == &s[0]
s4 := (*[4]byte)(s)      // panics: len([4]byte) > len(s)

var t []string
t0 := [0]string(t)       // ok for nil slice t
t1 := (*[0]string)(t)    // t1 == nil
t2 := (*[1]string)(t)    // panics: len([1]string) > len(t)

u := make([]byte, 0)
u0 := (*[0]byte)(u)      // u0 != nil

Try as I might, I can’t think of much to add to what the spec says on this point. It’s pretty straight forward, I think. The only thing I’ll call out is the fact that when you convert a slice to an array, the new array does not share the same backing array as the slice:

s := []int{1, 2, 3, 4}
a := [4]int(s)
a[0] = 0
s[3] = 99
fmt.Println(s, a) // [1 2 3 99] [0 2 3 4]

However, converting a slice to an array pointer does:

s := []int{1, 2, 3, 4}
a := (*[4]int)(s)
a[0] = 0
s[3] = 99
fmt.Println(s, a) // [0 2 3 99] [0 2 3 99]

Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe