从io.Reader到Go中的字符串 [英] From io.Reader to string in Go

查看:686
本文介绍了从io.Reader到Go中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 io.ReadCloser 对象(来自 http.Response 对象)。

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?

推荐答案

简单的答案是它不会高效,因为转换为字符串需要完成字节数组的完整拷贝。下面是适当的(非高效的)方法来做你想做的:

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.

此副本是作为保护机制完成的。字符串是不可变的。如果可以将[]字节转换为字符串,则可以更改字符串的内容。但是,go允许您使用不安全包禁用类型安全机制。使用不安全的软件包需要您自担风险。希望这个名字是一个足够好的警告。下面是我如何使用不安全的方法:

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. 没有任何保证可以在所有的编译器中使用。虽然这适用于9 gc编译器,但它依赖于官方规范中未提及的实现细节。你甚至不能保证这可以在所有架构上运行,也不能在gc中改变。换句话说,这是一个糟糕的主意。

  2. 该字符串是可变的!如果您在该缓冲区上进行任何调用,它将 改变字符串。请小心。

  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.

这篇关于从io.Reader到Go中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆