As long as no one modifies the bytes in the byteslice. Go can no longer enforce that the string is immutable with this hack.
On Mon, Sep 19, 2016 at 2:35 PM, <badrel...@gmail.com> wrote: > I don't like the extra allocation and copies involved when casting from > byte slice to string or vice versa just because one type or the other is > required. The code below reuses the data pointer and as far as I can tell > in my tests so far, it even works well with garbage collection. My question > is... why shouldn't I do this? > > > func fastStringToBytes(str string) []byte { > var b []byte > > strhdr := (*reflect.StringHeader)(unsafe.Pointer(&str)) > bythdr := (*reflect.SliceHeader)(unsafe.Pointer(&b)) > > d := strhdr.Data > l := strhdr.Len > > // strhdr.Data = bythdr.Data > // strhdr.Len = bythdr.Len > > bythdr.Data = d > bythdr.Len = l > bythdr.Cap = l > > return b > } > > func fastBytesToString(b []byte) string { > var str string > > strhdr := (*reflect.StringHeader)(unsafe.Pointer(&str)) > bythdr := (*reflect.SliceHeader)(unsafe.Pointer(&b)) > > // d := strhdr.Data > // l := strhdr.Len > > strhdr.Data = bythdr.Data > strhdr.Len = bythdr.Len > > // bythdr.Data = d > // bythdr.Len = l > // bythdr.Cap = l > > return str > } > > -- > 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. > For more options, visit https://groups.google.com/d/optout. > -- 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. For more options, visit https://groups.google.com/d/optout.