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
CodePudding user response:
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
. Ifa
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 iflen(s)
is less thanN
.- [...]
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).