The implementation of io.WriteString appears to allocate a new byte slice
and copy the string into it:

w.Write([]byte(s))

Many third party libraries avoid the allocation and copy with techniques
like:

var b []byte
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
bh.Data = sh.Data
bh.Len = sh.Len
bh.Cap = sh.Len
w.Write(b)

I've seen so many different packages do this that it almost seems like a
preferred idiom.  Yet, it doesn't seem to be guaranteed safe by the rules
in the "unsafe" package documentation; rule 6 comes close to allowing it
but doesn't quite get there.  And the fact that the standard library
doesn't use it, in an obviously applicable place, is telling.

So, what's the deal here?  Is it safe or not?  Can I use it in my own
code?  Must I shun libraries that use it?  (Must I read the source code of
every library I use, to see whether it uses it?)

-- 
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/CAAnpqKHoA74DfM5765vUfrH4V6RpBxg1DTkfn3ScN6MhjQwRTQ%40mail.gmail.com.

Reply via email to