On Thursday, December 13, 2012 8:26:04 PM UTC-7, Jay Weisskopf wrote:
Thanks. That's pretty interesting. So Go auto-magically creates a
slice for you if you index an array that way?
It's not too much of a magic trick, considering that slices are just a struct roughly like:
struct {
data unsafe.Pointer,
len, cap int
}
Due to this, an "automagic slice" of a 20mb string is exactly as cheap as an automagic slice of a 20 byte string, since no copies are involved.
Go is not C. A "string" in Go is like a slice header (that struct above), except it does not have a cap, and very specifically, a Go string consisting of 20 null bytes still has a "string length" of 20. In Go, there is no '\0': it's '\x00', since '\0' is not all that useful here. All this means that no matter the length of your string, you always have length information immediately available for the low cost of the size of an int (4-8 bytes), as opposed to regular C strings, which have linear-time length determinations and are susceptible to a large number of problems.