Last week covered a lot of ground but that articled linked last week did not cover another aspect of Go that might bite you.
It is tempting to think of Go as a functional language. At least it was for me and I think it is due to the lack of objects and focus on functions. Hence it is easy to think some built in functions behave in a functional way. But they don't. And if you read the documentation there is no doubt how these functions behave but how often do you really read documentation...
A common misunderstanding is that append always return a new slice and hence you can reuse a slice in a loop if there is a common slice prefix you want to use. But that is not the case. In Go append returns a new slice only if more memory needs to be allocated for the underlying array.
If you are a C programmer the best analogy here is realloc which may or may not return the same memory address. The fact that append works this way in Go is actually no surprise if you think about what the creators of Go created before Go...
No comments:
Post a Comment