Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of slice to array pointer

As mentioned in Spec, Converting a slice to an array pointer yields a pointer to the underlying array of the slice.

s := make([]byte, 2, 4)
s0 := (*[0]byte)(s)      // s0 != nil

But compiler gives error: cannot convert s (variable of type []byte) to *[0]byte

like image 392
overexchange Avatar asked Sep 18 '25 10:09

overexchange


1 Answers

This conversion was added to the language in Go 1.17.

Changes to the language

Go 1.17 includes three small enhancements to the language.

  • Conversions from slice to array pointer: An expression s of type []T may now be converted to array pointer type *[N]T. If a is the result of such a conversion, then corresponding indices that are in range refer to the same underlying elements: &a[i] == &s[i] for 0 <= i < N. The conversion panics if len(s) is less than N.
  • [...]

This means you need Go 1.17 or newer to use such conversion. It works well on the Go Playground (currently the playground uses the latest Go 1.19).

like image 134
icza Avatar answered Sep 20 '25 02:09

icza