duanli5662 2012-03-10 05:19
浏览 124


I have an io.ReadCloser object (from an http.Response object).

What's the most efficient way to convert the entire stream to a string object?

  • 写回答

6条回答 默认 最新

  • doudong3570 2012-03-10 18:33

    The short answer is that it it will not be efficient because converting to a string requires doing a complete copy of the byte array. Here is the proper (non-efficient) way to do what you want:

    buf := new(bytes.Buffer)
    s := buf.String() // Does a complete copy of the bytes in the buffer.

    This copy is done as a protection mechanism. Strings are immutable. If you could convert a []byte to a string, you could change the contents of the string. However, go allows you to disable the type safety mechanisms using the unsafe package. Use the unsafe package at your own risk. Hopefully the name alone is a good enough warning. Here is how I would do it using unsafe:

    buf := new(bytes.Buffer)
    b := buf.Bytes()
    s := *(*string)(unsafe.Pointer(&b))

    There we go, you have now efficiently converted your byte array to a string. Really, all this does is trick the type system into calling it a string. There are a couple caveats to this method:

    1. There are no guarantees this will work in all go compilers. While this works with the plan-9 gc compiler, it relies on "implementation details" not mentioned in the official spec. You can not even guarantee that this will work on all architectures or not be changed in gc. In other words, this is a bad idea.
    2. That string is mutable! If you make any calls on that buffer it will change the string. Be very careful.

    My advice is to stick to the official method. Doing a copy is not that expensive and it is not worth the evils of unsafe. If the string is too large to do a copy, you should not be making it into a string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 ensp如何拼通IP地址
  • ¥15 saber软件导入Ibis模型报错
  • ¥15 商城生产日期批次库存问题
  • ¥15 esp8266控制共阳极wrgb灯板无法关闭所有led灯
  • ¥100 python读取速度问题
  • ¥15 stm32f407使用DMA问题
  • ¥15 您好 这个API接口该怎么弄 网站搭建好了 API也有 现在就不知道该怎么填写API 不知道怎么用
  • ¥88 用uniapp写一个多端的程序,用到高德地图,用高德的JSAPI吗?
  • ¥20 关于#c++#的问题:水果店管理系统
  • ¥30 dbLinq最新版linq sqlite