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 t开发者_运维百科hen 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!
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.
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.
精彩评论