tags:

views:

59

answers:

2

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!

+2  A: 

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.

newacct
That's not 100% true, though close enough. Strings are treated differently than byte-arrays.
cthom06
Just curious, how to check when end of string (or end of char) reached? Or can I read char by char (using cast) to build the string from the connection?
helios
+2  A: 

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.

Andrew Gerrand