英文:
Reading utf8-encoded data from a connection, using Go
问题
我可以使用io.WriteString轻松地将字符串写入连接。
然而,我似乎无法轻松地从连接中读取字符串。我只能从连接中读取字节,然后必须将其转换为字符串。
假设这些字节表示一个utf8编码的字符串,我该如何将它们转换为字符串形式?
(编辑:或者,我如何简单地从连接中读取一个字符串?)
谢谢!
英文:
I can easily write a string to a connection using io.WriteString.
However, I can't seem to easily read a string from a connection. The only thing I can read from the connection are bytes, which, it seems, I must then somehow convert into a string.
Assuming the bytes represent a utf8-encoded string, how would I convert them to string form?
(Edit: alternatively, how could I simply read a string from a connection?)
Thanks!
答案1
得分: 4
在标准库中可以找到一个适合你目的的方便工具:bytes.Buffer
(请参阅包文档)。
假设你有一个实现了io.Reader
接口的对象(也就是说,它有一个具有Read([]byte) (int, os.Error)
签名的方法)。
一个常见的例子是os.File
:
f, err := os.Open("/etc/passwd", os.O_RDONLY, 0644)
如果你想将该文件的内容读取到一个字符串中,只需创建一个bytes.Buffer
(它的零值是一个可用的缓冲区,所以你不需要调用构造函数):
var b bytes.Buffer
使用io.Copy
将文件的内容复制到缓冲区中:
n, err := io.Copy(b, f)
(使用b.ReadFrom(f)
是使用io.Copy
的另一种选择 - 它们基本上是相同的。)
然后调用缓冲区的String方法将缓冲区的内容作为字符串检索出来:
s := b.String()
bytes.Buffer
会自动增长以存储文件的内容,所以你不需要担心分配和增长byte
切片等问题。
英文:
A handy tool that will suit your purpose can be found in the standard library: bytes.Buffer
(see the package docs).
Say you have an object that implements io.Reader
(that is, it has a method with the signature Read([]byte) (int, os.Error)
).
A common example is an os.File
:
f, err := os.Open("/etc/passwd", os.O_RDONLY, 0644)
If you wanted to read the contents of that file into a string, simply create a bytes.Buffer
(its zero-value is a ready-to-use buffer, so you don't need to call a constructor):
var b bytes.Buffer
Use io.Copy
to copy the file's contents into the buffer:
n, err := io.Copy(b, f)
(An alternative to using io.Copy
would be b.ReadFrom(f)
- they're more or less the same.)
And call the buffer's String method to retrieve the buffer's contents as a string:
s := b.String()
The bytes.Buffer
will automatically grow to store the contents of the file, so you don't need to worry about allocating and growing byte
slices, etc.
答案2
得分: 2
你可以将字节切片直接转换为字符串:
var foo []byte
var bar string = string(foo)
这里没有涉及编码/解码,因为字符串只是字节的数组。
英文:
You can just cast a slice of bytes into a string:
var foo []byte
var bar string = string(foo)
There is no encoding/decoding involved, because strings are just treated as arrays of bytes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论