必承其重 | 欲带皇冠 2012-03-10 05:19 采纳率: 0%
浏览 1059
已采纳

在 Go 中从 io.Reader 到 string

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?

转载于:https://stackoverflow.com/questions/9644139/from-io-reader-to-string-in-go

  • 写回答

6条回答 默认 最新

  • perhaps? 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)
    buf.ReadFrom(yourReader)
    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)
    buf.ReadFrom(yourReader)
    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)