From io.Reader to string in Go -
i have io.readcloser
object (from http.response
object).
what's efficient way convert entire stream string
object?
the short answer it not efficient because converting string requires doing complete copy of byte array. here proper (non-efficient) way want:
buf := new(bytes.buffer) buf.readfrom(yourreader) s := buf.string() // complete copy of bytes in buffer.
this copy done protection mechanism. strings immutable. if convert []byte string, change contents of string. however, go allows disable type safety mechanisms using unsafe package. use unsafe package @ own risk. name alone enough warning. here how using unsafe:
buf := new(bytes.buffer) buf.readfrom(yourreader) b := buf.bytes() s := *(*string)(unsafe.pointer(&b))
there go, have efficiently converted byte array string. really, trick type system calling string. there couple caveats method:
- there no guarantees work in go compilers. while works plan-9 gc compiler, relies on "implementation details" not mentioned in official spec. can not guarantee work on architectures or not changed in gc. in other words, bad idea.
- that string mutable! if make calls on buffer will change string. careful.
my advice stick official method. doing copy not that expensive , not worth evils of unsafe. if string large copy, should not making string.
Comments
Post a Comment