Thanks Ian, that's a very interesting solution.

Is there a solution for going in the other direction? Although I excluded 
it from the initial post, it was only to reduce the size of the discussion. 
I would also like to implement

func BytesToString(b []byte) string { 

I don't clearly see how to avoid using the StringHeader in this case.


On Wednesday, 18 September 2019 22:46:44 UTC+2, Ian Lance Taylor wrote:
> On Wed, Sep 18, 2019 at 2:42 AM Francis < 
> <javascript:>> 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 view this discussion on the web visit

Reply via email to