On Wed, Sep 18, 2019 at 2:42 AM Francis <francissteph...@gmail.com> wrote: > > I am looking at the correct way to convert from a byte slice to a string and > back with no allocations. All very unsafe. > > I think these two cases are fairly symmetrical. So to simplify the discussion > below I will only talk about converting from a string to []byte. > > func StringToBytes(s string) (b []byte)
No reason to use SliceHeader, and avoiding SliceHeader avoids the problems you discuss. func StringToBytes(s string) []byte { const max = 0x7fff0000 if len(s) > max { panic("string too long") } return (*[max]byte)(unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&s)).Data))[:len(s):len(s)] } Of course, as you say, you must not mutate the returned []byte. Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcUOEnKckCFfb3ujYFtqOk3XdKvig%2BSeg7eb91t40VPMMw%40mail.gmail.com.