Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

As she points out though, a lot of dynamic languages don’t behave this way. A string after all points to a heap allocation; so it’s not unreasonable to think of a string as a pointer.


I've several times answered questions from people coming from dynamic languages that ask lots of questions about Go pointers. And the answer is, actually, since Go lacks pointer arithmetic, Go pointers work the way you're used to things working. It's the Go non-pointers that are the new bizarre thing you're not used to!

So there is definitely a common language heritage that will find the behavior of value copies in Go surprising. I came into Go with compiled language experience but I'd been exclusively in dynamic scripting languages exclusively for over a decade. I had to remind myself about this as well.


In those languages, nearly everything is a pointer, they just don't call it that, which causes unnecessary confusion when you need to understand what's really happening. (E.g., in Java, a String is a pointer to a string, not a string; but an int is just an int, not a pointer to an int.)


It’s how structs work in C though, and Go is spiritually very close to C, including explicit pointer types, address-taking and dereferencing.


Not necessarily. A string in C is usually a char. If you have a struct with a char and you copy it, you copy the pointer to the backing memory. This is analogous to Go which also has a String be a pointer to the heap, but the behavior is different.

Go’s String is a char* that behaves like a char[] when copied.


Is there a typo in this? C strings are not usually structs at all. Structs also do not behave differently if they contain a char.


I think the two *s merged into an italic there


> Go’s String is a char* that behaves like a char[] when copied.

Uhh, no. A go string is (effectively) a pointer to an immutable string of characters. When you do a = b, both a and b point to the same string (i.e. each is its own string struct, containing a pointer to the exact same array of character data).

But if you try to get a byte[] from it, THEN it makes a copy.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: