Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading